Basics: On Page Script

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12
At a glance
Powered by AI
Some of the key takeaways from the document include JavaScript basics like variables, data types, operators, and loops. It also covers more advanced topics like promises and asynchronous programming.

The main types of JavaScript loops covered are for loops, while loops, do-while loops, and for-of loops. Each has their own use cases for iterating over elements in an array or repeating an action a certain number of times.

Common JavaScript data types include numbers, strings, booleans, arrays, objects, functions, dates, and special values like null and undefined. The data type of a variable determines what operations and properties it can use.

Basics

On page script

1 <script type="text/javascript">  ...


2 </script>

Include external JS file

1 <script src="filename.js"></script>

Delay - 1 second timeout

1 setTimeout(function () {
2
3 }, 1000);

Functions

1 function addNumbers(a, b) {
2 return a + b; ;
3 }
4 x = addNumbers(1, 2);

Edit DOM element

1 document.getElementById("elementID").innerHTML = "Hello World!";

Output

1 console.log(a);             // write to the browser console


2 document.write(a);          // write to the HTML
3 alert(a);                   // output in an alert box
4 confirm("Really?");         // yes/no dialog, returns true/false depending on user
click
5 prompt("Your age?","0");    // input dialog. Second argument is the initial value

Comments

1 /* Multi line
2 comment */
3 // One line
Loops
For Loop

1 for (var i = 0; i < 10; i++) {


2 document.write(i + ": " + i*3 + "<br />");
3 }
4 var sum = 0;
5 for (var i = 0; i < a.length; i++) {
6 sum + = a[i];
7 }               // parsing an array
8 html = "";
9 for (var i of custOrder) {
10 html += "<li>" + i + "</li>";
11 }

While Loop

1 var i = 1;                      // initialize


2 while (i < 100) {               // enters the cycle if statement is true
3 i *= 2;                     // increment to avoid infinite loop
4 document.write(i + ", ");   // output
5 }

Do While Loop

1 var i = 1;                      // initialize


2 do {                            // enters cycle at least once
3 i *= 2;                     // increment to avoid infinite loop
4 document.write(i + ", ");   // output
5 } while (i < 100)               // repeats cycle if statement is true at the end

Break

1 for (var i = 0; i < 10; i++) {


2 if (i == 5) { break; }          // stops and exits the cycle
3 document.write(i + ", ");       // last output number is 4
4 }

Continue

1 for (var i = 0; i < 10; i++) {


2 if (i == 5) { continue; }       // skips the rest of the cycle
3 document.write(i + ", ");       // skips 5
4 }

If - Else
1 if ((age >= 14) && (age < 19)) {        // logical condition
2 status = "Eligible.";               // executed if condition is true
3 } else {                                // else block is optional
4 status = "Not eligible.";           // executed if condition is false
5 }

Switch Statement

1 switch (new Date().getDay()) {      // input is current day


2 case 6:                         // if (day == 6)
3 text = "Saturday";          
4 break;
5 case 0:                         // if (day == 0)
6 text = "Sunday";
7 break;
8 default:                        // else...
9 text = "Whatever";
10 }

Variables
1 var a;                          // variable
2 var b = "init";                 // string
3 var c = "Hi" + " " + "Joe";     // = "Hi Joe"
4 var d = 1 + 2 + "3";            // = "33"
5 var e = [2,3,5,8];              // array
6 var f = false;                  // boolean
7 var g = /()/;                   // RegEx
8 var h = function(){};           // function object
9 const PI = 3.14;                // constant
10 var a = 1, b = 2, c = a + b;    // one line
11 let z = 'zzz';                  // block scope local variable

Strict mode

1 "use strict";   // Use strict mode to write secure code


2 x = 1;          // Throws an error because variable is not declared

Values

1 false, true                     // boolean


2 18, 3.14, 0b10011, 0xF6, NaN    // number
3 "flower", 'John'                // string
4 undefined, null , Infinity      // special

Operators

1 a = b + c - d;      // addition, substraction


2 a = b * (c / d);    // multiplication, division
3 x = 100 % 48;       // modulo. 100 / 48 remainder = 4
4 a++; b--;           // postfix increment and decrement
Bitwise operators

& AND 5 & 1 (0101 & 0001) 1 (1)

| OR 5 | 1 (0101 | 0001) 5 (101)

~ NOT ~ 5 (~0101) 10 (1010)

^ XOR 5 ^ 1 (0101 ^ 0001) 4 (100)

<< left shift 5 << 1 (0101 << 1) 10 (1010)

>> right shift 5 >> 1 (0101 >> 1) 2 (10)

>>> zero fill right shift 5 >>> 1 (0101 >>> 1) 2 (10)

Arithmetic

1 a * (b + c)         // grouping
2 person.age          // member
3 person[age]         // member
4 !(a == b)           // logical not
5 a != b              // not equal
6 typeof a            // type (number, object, function...)
7 x << 2  x >> 3      // minary shifting
8 a = b               // assignment
9 a == b              // equals
10 a != b              // unequal
11 a === b             // strict equal
12 a !== b             // strict unequal
13 a < b   a > b       // less and greater than
14 a <= b  a >= b      // less or equal, greater or eq
15 a += b              // a = a + b (works with - * %...)
16 a && b              // logical and
17 a || b              // logical or

Data Types
1 var age = 18;                           // number
2 var name = "Jane";                      // string
3 var name = {first:"Jane", last:"Doe"};  // object
4 var truth = false;                      // boolean
5 var sheets = ["HTML","CSS","JS"];       // array
6 var a; typeof a;                        // undefined
7 var a = null;                           // value null

Objects
1 var student = {                 // object name
2 firstName:"Jane",           // list of properties and values
3 lastName:"Doe",
4 age:18,
5 height:170,
6 fullName : function() {     // object function
7   return this.firstName + " " + this.lastName;
8 }
9 };
10 student.age = 19;           // setting value
11 student[age]++;             // incrementing
12 name = student.fullName();  // call object function

Strings
1 var abc = "abcdefghijklmnopqrstuvwxyz";
2 var esc = 'I don\'t \n know';   // \n new line
3 var len = abc.length;           // string length
4 abc.indexOf("lmno");            // find substring, -1 if doesn't contain
5 abc.lastIndexOf("lmno");        // last occurance
6 abc.slice(3, 6);                // cuts out "def", negative values count from behind
7 abc.replace("abc","123");       // find and replace, takes regular expressions
8 abc.toUpperCase();              // convert to upper case
9 abc.toLowerCase();              // convert to lower case
10 abc.concat(" ", str2);          // abc + " " + str2
11 abc.charAt(2);                  // character at index: "c"
12 abc[2];                         // unsafe, abc[2] = "C" doesn't work
13 abc.charCodeAt(2);              // character code at index: "c" -> 99
14 abc.split(",");                 // splitting a string on commas gives an array
15 abc.split("");                  // splitting on characters
16 128.toString(16);               // number to hex(16), octal (8) or binary (2)

Events
1 <button onclick="myFunction();">
2 Click here
3 </button>

Mouse
onclick, oncontextmenu, ondblclick, onmousedown, onmouseenter, onmouseleave, onmousemove, onmouseover,
onmouseout, onmouseup

Keyboard
onkeydown, onkeypress, onkeyup
Frame
onabort, onbeforeunload, onerror, onhashchange, onload, onpageshow, onpagehide, onresize, onscroll, onunload

Form
onblur, onchange, onfocus, onfocusin, onfocusout, oninput, oninvalid, onreset, onsearch, onselect, onsubmit

Drag
ondrag, ondragend, ondragenter, ondragleave, ondragover, ondragstart, ondrop

Clipboard
oncopy, oncut, onpaste

Media
onabort, oncanplay, oncanplaythrough, ondurationchange, onended, onerror, onloadeddata, onloadedmetadata, onloadstart,
onpause, onplay, onplaying, onprogress, onratechange, onseeked, onseeking, onstalled, onsuspend, ontimeupdate,
onvolumechange, onwaiting

Animation
animationend, animationiteration, animationstart

Miscellaneous
transitionend, onmessage, onmousewheel, ononline, onoffline, onpopstate, onshow, onstorage, ontoggle, onwheel,
ontouchcancel, ontouchend, ontouchmove, ontouchstart

Numbers and Math


1 var pi = 3.141;
2 pi.toFixed(0);          // returns 3
3 pi.toFixed(2);          // returns 3.14 - for working with money
4 pi.toPrecision(2)       // returns 3.1
5 pi.valueOf();           // returns number
6 Number(true);           // converts to number
7 Number(new Date())      // number of milliseconds since 1970
8 parseInt("3 months");   // returns the first number: 3
9 parseFloat("3.5 days"); // returns 3.5
10 Number.MAX_VALUE        // largest possible JS number
11 Number.MIN_VALUE        // smallest possible JS number
12 Number.NEGATIVE_INFINITY// -Infinity
13 Number.POSITIVE_INFINITY// Infinity

Math.

1 var pi = Math.PI;       // 3.141592653589793


2 Math.round(4.4);        // = 4 - rounded
3 Math.round(4.5);        // = 5
4 Math.pow(2,8);          // = 256 - 2 to the power of 8
5 Math.sqrt(49);          // = 7 - square root
6 Math.abs(-3.14);        // = 3.14 - absolute, positive value
7 Math.ceil(3.14);        // = 4 - rounded up
8 Math.floor(3.99);       // = 3 - rounded down
9 Math.sin(0);            // = 0 - sine
10 Math.cos(Math.PI);      // OTHERS: tan,atan,asin,acos,
11 Math.min(0, 3, -2, 2);  // = -2 - the lowest value
12 Math.max(0, 3, -2, 2);  // = 3 - the highest value
13 Math.log(1);            // = 0 natural logarithm
14 Math.exp(1);            // = 2.7182pow(E,x)
15 Math.random();          // random number between 0 and 1
16 Math.floor(Math.random() * 5) + 1;  // random integer, from 1 to 5

Constants like Math.PI:


E, PI, SQRT2, SQRT1_2, LN2, LN10, LOG2E, Log10E

Dates
Thu Apr 22 2021 14:20:39 GMT-0300 (Brasilia Standard Time)

1 var d = new Date();

1619112039621 miliseconds passed since 1970

1 Number(d)
2 Date("2017-06-23");                 // date declaration
3 Date("2017");                       // is set to Jan 01
4 Date("2017-06-23T12:00:00-09:45");  // date - time YYYY-MM-DDTHH:MM:SSZ
5 Date("June 23 2017");               // long date format
6 Date("Jun 23 2017 07:45:00 GMT+0100 (Tokyo Time)"); // time zone

Get Times

1 var d = new Date();


2 a = d.getDay();     // getting the weekday
3
4 getDate();          // day as a number (1-31)
5 getDay();           // weekday as a number (0-6)
6 getFullYear();      // four digit year (yyyy)
7 getHours();         // hour (0-23)
8 getMilliseconds();  // milliseconds (0-999)
9 getMinutes();       // minutes (0-59)
10 getMonth();         // month (0-11)
11 getSeconds();       // seconds (0-59)
12 getTime();          // milliseconds since 1970

Setting part of a date


1 var d = new Date();
2 d.setDate(d.getDate() + 7); // adds a week to a date
3
4 setDate();          // day as a number (1-31)
5 setFullYear();      // year (optionally month and day)
6 setHours();         // hour (0-23)
7 setMilliseconds();  // milliseconds (0-999)
8 setMinutes();       // minutes (0-59)
9 setMonth();         // month (0-11)
10 setSeconds();       // seconds (0-59)
11 setTime();          // milliseconds since 1970)

Arrays
1 var dogs = ["Bulldog", "Beagle", "Labrador"];
2 var dogs = new Array("Bulldog", "Beagle", "Labrador");  // declaration
3
4 alert(dogs[1]);             // access value at index, first item being [0]
5 dogs[0] = "Bull Terier";    // change the first item
6
7 for (var i = 0; i < dogs.length; i++) {     // parsing with array.length
8 console.log(dogs[i]);
9 }

Methods

1 dogs.toString();                        // convert to string: results


"Bulldog,Beagle,Labrador"
2 dogs.join(" * ");                       // join: "Bulldog * Beagle * Labrador"
3 dogs.pop();                             // remove last element
4 dogs.push("Chihuahua");                 // add new element to the end
5 dogs[dogs.length] = "Chihuahua";        // the same as push
6 dogs.shift();                           // remove first element
7 dogs.unshift("Chihuahua");              // add new element to the beginning
8 delete dogs[0];                         // change element to undefined (not
recommended)
9 dogs.splice(2, 0, "Pug", "Boxer");      // add elements (where, how many to remove,
element list)
10 var animals = dogs.concat(cats,birds);  // join two arrays (dogs followed by cats
and birds)
11 dogs.slice(1,4);                        // elements from [1] to [4-1]
12 dogs.sort();                            // sort string alphabetically
13 dogs.reverse();                         // sort string in descending order
14 x.sort(function(a, b){return a - b});   // numeric sort
15 x.sort(function(a, b){return b - a});   // numeric descending sort
16 highest = x[0];                         // first item in sorted array is the lowest
(or highest) value
17 x.sort(function(a, b){return 0.5 - Math.random()});     // random order sort

concat, copyWithin, every, fill, filter, find, findIndex, forEach, indexOf, isArray, join, lastIndexOf, map, pop, push, reduce,
reduceRight, reverse, shift, slice, some, sort, splice, toString, unshift, valueOf
Global Functions
1 eval();                     // executes a string as if it was script code
2 String(23);                 // return string from number
3 (23).toString();            // return string from number
4 Number("23");               // return number from string
5 decodeURI(enc);             // decode URI. Result: "my page.asp"
6 encodeURI(uri);             // encode URI. Result: "my%page.asp"
7 decodeURIComponent(enc);    // decode a URI component
8 encodeURIComponent(uri);    // encode a URI component
9 isFinite();                 // is variable a finite, legal number
10 isNaN();                    // is variable an illegal number
11 parseFloat();               // returns floating point number of string
12 parseInt();                 // parses a string and returns an integer

Regular Expressions
1 var a = str.search(/CheatSheet/i);

Modifiers
i*perform case-insensitive matching*

g*perform a global match*

m*perform multiline matching*

Patterns
*Escape character*

\d*find a digit*

\s*find a whitespace character*

\b*find match at beginning or end of a word*

n+*contains at least one n*

n**contains zero or more occurrences of n*

n?*contains zero or one occurrences of n*

^*Start of string*

$*End of string*

\uxxxx*find the Unicode character*

.*Any single character*

(a|b)*a or b*

(...)*Group section*

[abc]*In range (a, b or c)*


[0-9]*any of the digits between the brackets*

[^abc]*Not in range*

\s*White space*

a?*Zero or one of a*

a**Zero or more of a*

a*?*Zero or more, ungreedy*

a+*One or more of a*

a+?*One or more, ungreedy*

a{2}*Exactly 2 of a*

a{2,}*2 or more of a*

a{,5}*Up to 5 of a*

a{2,5}*2 to 5 of a*

a{2,5}?*2 to 5 of a, ungreedy*

[:punct:]*Any punctuation symbol*

[:space:]*Any space character*

[:blank:]*Space or tab*

Errors
1 try {                           // block of code to try
2 undefinedFunction();
3 }
4 catch(err) {                    // block to handle errors
5 console.log(err.message);
6 }

Throw error

1 throw "My error message";   // throw a text

Input validation

1 var x = document.getElementById("mynum").value; // get input value


2 try {
3 if(x == "")  throw "empty";                 // error cases
4 if(isNaN(x)) throw "not a number";
5 x = Number(x);
6 if(x > 10)   throw "too high";
7 }
8 catch(err) {                                    // if there's an error
9 document.write("Input is " + err);          // output error
10 console.error(err);                         // write the error in console
11 }
12 finally {
13 document.write("</br />Done");              // executed regardless of the try /
catch result
14 }

Error name values


RangeError*A number is "out of range"*

ReferenceError*An illegal reference has occurred*

SyntaxError*A syntax error has occurred*

TypeError*A type error has occurred*

URIError*An encodeURI() error has occurred*

JSON
1 var str = '{"names":[' +                    // crate JSON object
2 '{"first":"Hakuna","lastN":"Matata" },' +
3 '{"first":"Jane","lastN":"Doe" },' +
4 '{"first":"Air","last":"Jordan" }]}';
5 obj = JSON.parse(str);                      // parse
6 document.write(obj.names[1].first);         // access

Send

1 var myObj = { "name":"Jane", "age":18, "city":"Chicago" };  // create object


2 var myJSON = JSON.stringify(myObj);                         // stringify
3 window.location = "demo.php?x=" + myJSON;                   // send to php

Storing and retrieving

1 myObj = { "name":"Jane", "age":18, "city":"Chicago" };


2 myJSON = JSON.stringify(myObj);                 // storing data
3 localStorage.setItem("testJSON", myJSON);  
4 text = localStorage.getItem("testJSON");        // retrieving data
5 obj = JSON.parse(text);
6 document.write(obj.name);

Promises
1 function sum (a, b) {
2 return Promise(function (resolve, reject) {
3 setTimeout(function () {                                       // send the response
after 1 second
4   if (typeof a !== "number" || typeof b !== "number") {        // testing input
types
5 return reject(new TypeError("Inputs must be numbers"));
6   }
7   resolve(a + b);
8 }, 1000);
9 });
10 }
11 var myPromise = sum(10, 5);
12 myPromsise.then(function (result) {
13 document.write(" 10 + 5: ", result);
14 return sum(null, "foo");              // Invalid data and return another promise
15 }).then(function () {                   // Won't be called because of the error
16 }).catch(function (err) {               // The catch handler is called instead,
after another second
17 console.error(err);                   // => Please provide two numbers to sum.
18 });

States
pending, fulfilled, rejected

Properties
Promise.length, Promise.prototype

Methods
Promise.all(iterable), Promise.race(iterable), Promise.reject(reason), Promise.resolve(value)

You might also like