Job Ready Project Bundle
Best 125 Projects
JS CheatSheet
Basics ➤
Loops ↶ On page script
<script type="text/javascript"> ...
</script>
For Loop
for (var i = 0; i < 10; i++) { Include external JS file
document.write(i + ": " + i*3 + "<br />"); <script src="filename.js"></script>
}
var sum = 0; Delay - 1 second timeout
for (var i = 0; i < a.length; i++) { setTimeout(function () {
sum + = a[i];
} // parsing an array }, 1000);
html = "";
for (var i of custOrder) { Functions
html += "<li>" + i + "</li>"; function addNumbers(a, b) {
} return a + b; ;
}
While Loop
x = addNumbers(1, 2);
var i = 1; // initialize
while (i < 100) { // enters the cycle
Edit DOM element
i *= 2; // increment to avo
document.write(i + ", "); // output document.getElementById("elementID").innerHTML = "
}
Output
Do While Loop console.log(a); // write to the browse
var i = 1; // initialize document.write(a); // write to the HTML
do { // enters cycle at alert(a); // output in an alert
i *= 2; // increment to avo confirm("Really?"); // yes/no dialog, retu
document.write(i + ", "); // output prompt("Your age?","0"); // input dialog. Secon
} while (i < 100) // repeats cycle if
Comments
Break /* Multi line
for (var i = 0; i < 10; i++) { comment */
if (i == 5) { break; } // stops and ex // One line
document.write(i + ", "); // last output
}
Continue If - Else ⇵
for (var i = 0; i < 10; i++) {
if ((age >= 14) && (age < 19)) { // logical
if (i == 5) { continue; } // skips the re
status = "Eligible."; // execute
document.write(i + ", "); // skips 5
} else { // else bl
}
status = "Not eligible."; // execute
}
Switch Statement
Variables x switch (new Date().getDay()) { // input is cu
case 6: // if (day ==
var a; // variable
text = "Saturday";
var b = "init"; // string
break;
var c = "Hi" + " " + "Joe"; // = "Hi Joe"
case 0: // if (day ==
var d = 1 + 2 + "3"; // = "33"
text = "Sunday";
var e = [2,3,5,8]; // array
break;
var f = false; // boolean
default: // else...
var g = /()/; // RegEx
text = "Whatever";
var h = function(){}; // function object
}
const PI = 3.14; // constant
var a = 1, b = 2, c = a + b; // one line
let z = 'zzz'; // block scope loca
Strict mode Data Types ℜ
"use strict"; // Use strict mode to write secure
var age = 18; // number
x = 1; // Throws an error because variable
var name = "Jane"; // string
Values var name = {first:"Jane", last:"Doe"}; // object
false, true // boolean var truth = false; // boolean
18, 3.14, 0b10011, 0xF6, NaN // number var sheets = ["HTML","CSS","JS"]; // array
"flower", 'John' // string var a; typeof a; // undefin
var a = null; // value n
undefined, null , Infinity // special
Operators Objects
a = b + c - d; // addition, substraction var student = { // object name
firstName:"Jane", // list of propert
a = b * (c / d); // multiplication, division
lastName:"Doe",
x = 100 % 48; // modulo. 100 / 48 remainder =
a++; b--; // postfix increment and decrem age:18,
height:170,
Bitwise operators fullName : function() { // object function
return this.firstName + " " + this.lastName
5 & 1 (0101 &
& AND 1 (1) }
0001)
};
| OR 5 | 1 (0101 | 0001) 5 (101)
student.age = 19; // setting value
10
~ NOT ~ 5 (~0101) student[age]++; // incrementing
(1010)
name = student.fullName(); // call object functio
^ XOR 5 ^ 1 (0101 ^ 0001) 4 (100)
10
<< left shift 5 << 1 (0101 << 1)
(1010)
>> right shift 5 >> 1 (0101 >> 1) 2 (10) Strings ⊗
zero fill right 5 >>> 1 (0101 >>>
>>> 2 (10)
shift 1) var abc = "abcdefghijklmnopqrstuvwxyz";
var esc = 'I don\'t \n know'; // \n new line
Arithmetic var len = abc.length; // string length
a * (b + c) // grouping abc.indexOf("lmno"); // find substring,
person.age // member abc.lastIndexOf("lmno"); // last occurance
person[age] // member abc.slice(3, 6); // cuts out "def",
!(a == b) // logical not abc.replace("abc","123"); // find and replac
a != b // not equal abc.toUpperCase(); // convert to uppe
typeof a // type (number, object, functi abc.toLowerCase(); // convert to lowe
x << 2 x >> 3 // minary shifting abc.concat(" ", str2); // abc + " " + str
a = b // assignment abc.charAt(2); // character at in
a == b // equals abc[2]; // unsafe, abc[2]
a != b // unequal abc.charCodeAt(2); // character code
a === b // strict equal abc.split(","); // splitting a str
a !== b // strict unequal abc.split(""); // splitting on ch
a < b a > b // less and greater than 128.toString(16); // number to hex(1
a <= b a >= b // less or equal, greater or eq
a += b // a = a + b (works with - * %.
Events 🕖
a && b // logical and
Numbers and Math ∑
a || b // logical or
<button onclick="myFunction();">
var pi = 3.141;
Click here
pi.toFixed(0); // returns 3
</button>
pi.toFixed(2); // returns 3.14 - for worki
pi.toPrecision(2) // returns 3.1 Mouse
pi.valueOf(); // returns number
onclick, oncontextmenu, ondblclick, onmousedown,
Number(true); // converts to number
onmouseenter, onmouseleave, onmousemove,
Number(new Date()) // number of milliseconds s
onmouseover, onmouseout, onmouseup
parseInt("3 months"); // returns the first number
parseFloat("3.5 days"); // returns 3.5 Keyboard
Number.MAX_VALUE // largest possible JS numb onkeydown, onkeypress, onkeyup
Number.MIN_VALUE // smallest possible JS num
Number.NEGATIVE_INFINITY// -Infinity Frame
Number.POSITIVE_INFINITY// Infinity onabort, onbeforeunload, onerror, onhashchange, onload
onpageshow, onpagehide, onresize, onscroll, onunload
Math.
var pi = Math.PI; // 3.141592653589793 Form
Math.round(4.4); // = 4 - rounded onblur, onchange, onfocus, onfocusin, onfocusout,
Math.round(4.5); // = 5 oninput, oninvalid, onreset, onsearch, onselect, onsubmit
Math.pow(2,8); // = 256 - 2 to the power o
Math.sqrt(49); // = 7 - square root Drag
Math.abs(-3.14); // = 3.14 - absolute, posit ondrag, ondragend, ondragenter, ondragleave,
Math.ceil(3.14); // = 4 - rounded up ondragover, ondragstart, ondrop
Math.floor(3.99); // = 3 - rounded down
Math.sin(0); // = 0 - sine Clipboard
oncopy, oncut, onpaste
Math.cos(Math.PI); // OTHERS: tan,atan,asin,ac Media
Math.min(0, 3, -2, 2); // = -2 - the lowest value
onabort, oncanplay, oncanplaythrough, ondurationchange
Math.max(0, 3, -2, 2); // = 3 - the highest value onended, onerror, onloadeddata, onloadedmetadata,
Math.log(1); // = 0 natural logarithm onloadstart, onpause, onplay, onplaying, onprogress,
Math.exp(1); // = 2.7182pow(E,x) onratechange, onseeked, onseeking, onstalled,
Math.random(); // random number between 0 onsuspend, ontimeupdate, onvolumechange, onwaiting
Math.floor(Math.random() * 5) + 1; // random integ
Animation
Constants like Math.PI: animationend, animationiteration, animationstart
E, PI, SQRT2, SQRT1_2, LN2, LN10, LOG2E, Log10E
Miscellaneous
transitionend, onmessage, onmousewheel, ononline,
Dates 📆 onoffline, onpopstate, onshow, onstorage, ontoggle,
onwheel, ontouchcancel, ontouchend, ontouchmove,
Mon Feb 17 2020 13:42:03 GMT+0200 (Eastern European ontouchstart
Standard Time)
var d = new Date();
1581939723047 miliseconds passed since 1970
Number(d)
Arrays ≡
Date("2017-06-23"); // date declara var dogs = ["Bulldog", "Beagle", "Labrador"];
Date("2017"); // is set to Ja var dogs = new Array("Bulldog", "Beagle", "Labrado
Date("2017-06-23T12:00:00-09:45"); // date - time
Date("June 23 2017"); // long date fo alert(dogs[1]); // access value at ind
Date("Jun 23 2017 07:45:00 GMT+0100 (Tokyo Time)"); dogs[0] = "Bull Terier"; // change the first it
Get Times for (var i = 0; i < dogs.length; i++) { // par
var d = new Date(); console.log(dogs[i]);
a = d.getDay(); // getting the weekday }
Methods
getDate(); // day as a number (1-31)
getDay(); // weekday as a number (0-6) dogs.toString(); // convert
getFullYear(); // four digit year (yyyy) dogs.join(" * "); // join: "
getHours(); // hour (0-23) dogs.pop(); // remove
getMilliseconds(); // milliseconds (0-999) dogs.push("Chihuahua"); // add new
getMinutes(); // minutes (0-59) dogs[dogs.length] = "Chihuahua"; // the sam
getMonth(); // month (0-11) dogs.shift(); // remove
getSeconds(); // seconds (0-59) dogs.unshift("Chihuahua"); // add new
getTime(); // milliseconds since 1970 delete dogs[0]; // change
dogs.splice(2, 0, "Pug", "Boxer"); // add ele
Setting part of a date var animals = dogs.concat(cats,birds); // join tw
var d = new Date(); dogs.slice(1,4); // element
d.setDate(d.getDate() + 7); // adds a week to a dat dogs.sort(); // sort st
dogs.reverse(); // sort st
setDate(); // day as a number (1-31) x.sort(function(a, b){return a - b}); // numeric
setFullYear(); // year (optionally month and d x.sort(function(a, b){return b - a}); // numeric
setHours(); // hour (0-23) highest = x[0]; // first i
setMilliseconds(); // milliseconds (0-999) x.sort(function(a, b){return 0.5 - Math.random()})
setMinutes(); // minutes (0-59)
setMonth(); // month (0-11) concat, copyWithin, every, fill, filter, find, findIndex,
setSeconds(); // seconds (0-59) forEach, indexOf, isArray, join, lastIndexOf, map, pop,
setTime(); // milliseconds since 1970) push, reduce, reduceRight, reverse, shift, slice, some,
sort, splice, toString, unshift, valueOf
Global Functions () Regular Expressions \n
eval(); // executes a string as
var a = str.search(/CheatSheet/i);
String(23); // return string from n
(23).toString(); // return string from n
Number("23"); // return number from s Modifiers
decodeURI(enc); // decode URI. Result: i perform case-insensitive matching
encodeURI(uri); // encode URI. Result: g perform a global match
decodeURIComponent(enc); // decode a URI compone m perform multiline matching
encodeURIComponent(uri); // encode a URI compone
Patterns
isFinite(); // is variable a finite
isNaN(); // is variable an illeg \ Escape character
parseFloat(); // returns floating poi
\d find a digit
\s find a whitespace character
parseInt(); // parses a string and
\b
find match at beginning or end of a word
n+ contains at least one n
Errors ⚠ n*
contains zero or more occurrences of n
try { // block of code to n?
undefinedFunction();
contains zero or one occurrences of n
^ Start of string
}
catch(err) { // block to handle
console.log(err.message);
} JSON j
Throw error var str = '{"names":[' + // cra
throw "My error message"; // throw a text '{"first":"Hakuna","lastN":"Matata" },' +
'{"first":"Jane","lastN":"Doe" },' +
'{"first":"Air","last":"Jordan" }]}';
Input validation
obj = JSON.parse(str); // par
var x = document.getElementById("mynum").value; // document.write(obj.names[1].first); // acc
try {
if(x == "") throw "empty"; // Send
if(isNaN(x)) throw "not a number"; var myObj = { "name":"Jane", "age":18, "city":"Chi
x = Number(x); var myJSON = JSON.stringify(myObj);
if(x > 10) throw "too high"; window.location = "demo.php?x=" + myJSON;
}
catch(err) { // Storing and retrieving
document.write("Input is " + err); // myObj = { "name":"Jane", "age":18, "city":"Chicago
console.error(err); // myJSON = JSON.stringify(myObj); //
} localStorage.setItem("testJSON", myJSON);
finally { text = localStorage.getItem("testJSON"); //
document.write("</br />Done"); // obj = JSON.parse(text);
} document.write(obj.name);
Error name values
RangeError A number is "out of range"
ReferenceError
SyntaxError
An illegal reference has occurred
A syntax error has occurred Promises Þ
TypeError A type error has occurred
function sum (a, b) {
URIError An encodeURI() error has occurred
return Promise(function (resolve, reject) {
setTimeout(function () {
if (typeof a !== "number" || typeof b !== "
Useful Links ↵ }
return reject(new TypeError("Inputs must
resolve(a + b);
JS cleaner Obfuscator }, 1000);
Can I use? Node.js });
}
jQuery RegEx tester var myPromise = sum(10, 5);
myPromsise.then(function (result) {
document.write(" 10 + 5: ", result);
return sum(null, "foo"); // Invalid
}).then(function () { // Won't b
}).catch(function (err) { // The cat
console.error(err); // => Plea
});
States
pending, fulfilled, rejected
Properties
Promise.length, Promise.prototype
Methods
Promise.all(iterable), Promise.race(iterable),
Promise.reject(reason), Promise.resolve(value)
HTML Cheat Sheet is using cookies. | Terms and Conditions, Privacy Policy
ninja_webtech ©2020 HTMLCheatSheet.com