Basics: On Page Script
Basics: On Page Script
Basics: On Page Script
On page script
1 <script src="filename.js"></script>
1 setTimeout(function () {
2
3 }, 1000);
Functions
1 function addNumbers(a, b) {
2 return a + b; ;
3 }
4 x = addNumbers(1, 2);
Output
Comments
1 /* Multi line
2 comment */
3 // One line
Loops
For Loop
While Loop
Do While Loop
Break
Continue
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
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
Values
Operators
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
Math.
Dates
Thu Apr 22 2021 14:20:39 GMT-0300 (Brasilia Standard Time)
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
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
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*
Patterns
*Escape character*
\d*find a digit*
^*Start of string*
$*End of string*
(a|b)*a or b*
(...)*Group section*
[^abc]*Not in range*
\s*White space*
a?*Zero or one of a*
a**Zero or more of a*
a+*One or more of a*
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*
[: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
Input validation
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
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)