0% found this document useful (0 votes)
37 views

JavaScript Cheat Sheet - A Comprehensive List For Quick Reference - Clue Mediator

The document provides an overview of key JavaScript concepts across 14 sections: 1. Basics - How to include JS, functions, DOM manipulation 2. Variables - Declaring, assigning, and scoping variables 3. Data Types - Primitives like numbers, strings, booleans and objects 4. Strings - Methods for manipulating and extracting values from strings 5. Numbers and Math - Numeric values and operations, Math object methods 6. Arrays - Declaring, accessing, and manipulating array values and properties 7. Dates - Constructing Date objects and extracting temporal components
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views

JavaScript Cheat Sheet - A Comprehensive List For Quick Reference - Clue Mediator

The document provides an overview of key JavaScript concepts across 14 sections: 1. Basics - How to include JS, functions, DOM manipulation 2. Variables - Declaring, assigning, and scoping variables 3. Data Types - Primitives like numbers, strings, booleans and objects 4. Strings - Methods for manipulating and extracting values from strings 5. Numbers and Math - Numeric values and operations, Math object methods 6. Arrays - Declaring, accessing, and manipulating array values and properties 7. Dates - Constructing Date objects and extracting temporal components
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Table of Contents

Basics
Variables
Data Types
Strings
Numbers and Math
Arrays
Dates
JSON
Regular Expressions
If-Else
Loops
Global Functions
Events
Promises
Errors

1. Basics

On page script:

1 <script type="text/javascript">
2 ...
3 ...
4 </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 = "";

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 d
5 prompt("Your age?","0"); // input dialog. Second argument is th

Comments:

1 /* Multi line
2 comment */
3
4 // One line comment

2. 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 declare

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:

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


2 | OR 5 | 1 (0101 | 0001) 5 (101)
3 ~ NOT ~ 5 (~0101) 10 (1010)
4 ^ XOR 5 ^ 1 (0101 ^ 0001) 4 (100)
5 << left shift 5 << 1 (0101 << 1) 10 (1010)
6 >> right shift 5 >> 1 (0101 >> 1) 2 (10)
7 >>> 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

3. 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

4. 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 c
5 abc.lastIndexOf("lmno"); // last occurance
6 abc.slice(3, 6); // cuts out "def", negative values
7 abc.replace("abc","123"); // find and replace, takes regular
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 wo
13 abc.charCodeAt(2); // character code at index: "c" ->
14 abc.split(","); // splitting a string on commas gi
15 abc.split(""); // splitting on characters
16 128.toString(16); // number to hex(16), octal (8) or

5. 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
Math.floor(3.99); // = 3 - rounded down
8 Math.sin(0); // = 0 - sine
9 Math.cos(Math.PI); // OTHERS: tan,atan,asin,acos,
10 Math.min(0, 3, -2, 2); // = -2 - the lowest value
11 Math.max(0, 3, -2, 2); // = 3 - the highest value
12 Math.log(1); // = 0 natural logarithm
13 Math.exp(1); // = 2.7182pow(E,x)
14 Math.random(); // random number between 0 and 1
15 Math.floor(Math.random() * 5) + 1; // random integer, from 1 to 5
16

Constants like Math.PI:


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

6. Arrays

1 var dogs = ["Bulldog", "Beagle", "Labrador"];


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

Methods:

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


2 dogs.join(" * "); // join: "Bulldog * Beagle
3 dogs.pop(); // remove last element
4 dogs.push("Chihuahua"); // add new element to the
5 dogs[dogs.length] = "Chihuahua"; // the same as push
6 dogs.shift(); // remove first element
7 dogs.unshift("Chihuahua"); // add new element to the
8 delete dogs[0]; // change element to undef
9 dogs.splice(2, 0, "Pug", "Boxer"); // add elements (where, ho
10 var animals = dogs.concat(cats,birds); // join two arrays (dogs f
11 dogs.slice(1,4); // elements from [1] to [4
12 dogs.sort(); // sort string alphabetica
13 dogs.reverse(); // sort string in descendi
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 ar
17 x.sort(function(a, b){return 0.5 - Math.random()}); // random

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

7. Dates

1 Sat Jul 08 2023 12:18:24 GMT+0530 (India Standard Time)


2 var d = new Date();
3 1688798904720 miliseconds passed since 1970
4 Number(d)
5 Date("2017-06-23"); // date declaration
6 Date("2017"); // is set to Jan 01
7 Date("2017-06-23T12:00:00-09:45"); // date - time YYYY-MM-DDTHH:M
8 Date("June 23 2017"); // long date format
9 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)

8. 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" }; // cre


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

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);

9. Regular Expressions

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

Modifiers:

1 i perform case-insensitive matching


2 g perform a global match
3 m perform multiline matching

Patterns:

1 \ Escape character
2 \d find a digit
3 \s find a whitespace character
4 \b find match at beginning or end of a word
5 n+ contains at least one n
6 n* contains zero or more occurrences of n
7 n? contains zero or one occurrences of n
8 ^ Start of string
9 $ End of string
10 \uxxxx find the Unicode character
11 . Any single character
12 (a|b) a or b
13 (...) Group section
14 [abc] In range (a, b or c)
15 [0-9] any of the digits between the brackets
16 [^abc] Not in range
17 \s White space
18 a? Zero or one of a
19 a* Zero or more of a
20 a*? Zero or more, ungreedy
21 a+ One or more of a
22 a+? One or more, ungreedy
23 a{2} Exactly 2 of a
24 a{2,} 2 or more of a
25 a{,5} Up to 5 of a

10. If-Else

1 if ((age >= 14) && (age < 19)) { // logical condition


2 status = "Eligible."; // executed if condition i
3 } else { // else block is optional
4 status = "Not eligible."; // executed if condition i
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 }

11. 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 i
3 i *= 2; // increment to avoid infinite loo
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 loo
4 document.write(i + ", "); // output
5 } while (i < 100) // repeats cycle if statement is t

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 }

12. Global Functions

1 eval(); // executes a string as if it was scri


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 st
12 parseInt(); // parses a string and returns an inte

13. 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

14. Promises

1 function sum (a, b) {


2 return Promise(function (resolve, reject) {
3 setTimeout(function () {
4 if (typeof a !== "number" || typeof b !== "number") {
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 retu
15 }).then(function () { // Won't be called because
16
17 }).catch(function (err) { // The catch handler is ca
18 console.error(err); // => Please provide two
19 });

States
pending, fulfilled, rejected
Properties
Promise.length, Promise.prototype
Methods
Promise.all(iterable), Promise.race(iterable), Promise.reject(reason), Promise.resolve(value)

15. 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 e
9 document.write("Input is " + err); // output error
10 console.error(err); // write the error
11 }
12 finally {
13 document.write("</br />Done"); // executed regard
14 }

Error name values:

1 RangeError A number is "out of range"


2 ReferenceError An illegal reference has occurred
3 SyntaxError A syntax error has occurred
4 TypeError A type error has occurred
5 URIError An encodeURI() error has occurred

You might also like