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

JavaScript (JS) Cheat Sheet Online

Uploaded by

navii200000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

JavaScript (JS) Cheat Sheet Online

Uploaded by

navii200000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

5/21/24, 5:34 PM JavaScript (JS) Cheat Sheet Online

Hide comments

JS CheatSheet
Basics ➤ Loops

Ads 📣 On page script


<script type="text/javascript"> ...
For Loop
for (var i
</script> document.wr
}
Include external JS file var sum = 0
<script src="filename.js"></script> for (var i
sum + = a[i
Delay - 1 second timeout }
html = "";
setTimeout(function () {
for (var i
}, 1000); html += "<l
}
Functions
While Loop
function addNumbers(a, b) {
var i = 1;
return a + b; ;
} while (i <
x = addNumbers(1, 2); i *= 2;
document.wr
}
Edit DOM element
document.getElementById("elementID").innerHTML = "Hello World!"; Do While Lo
var i = 1;

If - Else ⇵ Output
console.log(a); // write to the browser console
do {
i *= 2;
document.write(a); // write to the HTML document.wr
if ((age >= 14) && (age < 19)) { // logical condition
alert(a); // output in an alert box } while (i
status = "Eligible."; // executed if condition is true
} else { // else block is optional confirm("Really?"); // yes/no dialog, returns true/false depending
status = "Not eligible."; // executed if condition is false prompt("Your age?","0"); // input dialog. Second argument is the initia Break
for (var i
}
Comments if (i == 5)
Switch Statement /* Multi line document.wr
comment */ }
switch (new Date().getDay()) { // input is current day
case 6: // if (day == 6) // One line
Continue
text = "Saturday";
for (var i
break;
if (i == 5)
case 0: // if (day == 0) Variables x document.wr
text = "Sunday";
}
break; var a; // variable
default: // else... var b = "init"; // string

📣
text = "Whatever"; var c = "Hi" + " " + "Joe"; // = "Hi Joe"
} var d = 1 + 2 + "3"; // = "33"
var e = [2,3,5,8]; // array
Ads
var f = false; // boolean
var g = /()/; // RegEx
Data Types ℜ var h = function(){}; // function object
const PI = 3.14; // constant
var age = 18; // number var a = 1, b = 2, c = a + b; // one line
var name = "Jane"; // string let z = 'zzz'; // block scope local variable
var name = {first:"Jane", last:"Doe"}; // object
var truth = false; // boolean Strict mode
var sheets = ["HTML","CSS","JS"]; // array "use strict"; // Use strict mode to write secure code
var a; typeof a; // undefined x = 1; // Throws an error because variable is not declared
var a = null; // value null
Values
Objects
false, true // boolean
var student = { // object name 18, 3.14, 0b10011, 0xF6, NaN // number
firstName:"Jane", // list of properties and values "flower", 'John' // string
lastName:"Doe", undefined, null , Infinity // special
age:18,
height:170, Operators
fullName : function() { // object function a = b + c - d; // addition, substraction
return this.firstName + " " + this.lastName; a = b * (c / d); // multiplication, division
} x = 100 % 48; // modulo. 100 / 48 remainder = 4
}; a++; b--; // postfix increment and decrement
student.age = 19; // setting value
student[age]++; // incrementing Bitwise operators
name = student.fullName(); // call object function & 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)
Strings ⊗ << left shift 5 << 1 (0101 << 1) 10 (1010)
var abc = "abcdefghijklmnopqrstuvwxyz"; >> right shift 5 >> 1 (0101 >> 1) 2 (10)
var esc = 'I don\'t \n know'; // \n new line >>> zero fill right shift 5 >>> 1 (0101 >>> 1) 2 (10)
var len = abc.length; // string length
Arithmetic
abc.indexOf("lmno"); // find substring, -1 if doesn't contain
abc.lastIndexOf("lmno"); // last occurance a * (b + c) // grouping
abc.slice(3, 6); // cuts out "def", negative values count f person.age // member
abc.replace("abc","123"); // find and replace, takes regular express person[age] // member
abc.toUpperCase(); // convert to upper case !(a == b) // logical not
abc.toLowerCase(); // convert to lower case a != b // not equal
abc.concat(" ", str2); // abc + " " + str2 typeof a // type (number, object, function...)
abc.charAt(2); // character at index: "c" x << 2 x >> 3 // minary shifting
abc[2]; // unsafe, abc[2] = "C" doesn't work a = b // assignment Event
abc.charCodeAt(2); // character code at index: "c" -> 99 a == b // equals
abc.split(","); // splitting a string on commas gives an a a != b // unequal <button onc
abc.split(""); // splitting on characters a === b // strict equal Click here
128.toString(16); // number to hex(16), octal (8) or binary a !== b // strict unequal </button>
a < b a > b // less and greater than
a <= b a >= b // less or equal, greater or eq Mouse

https://htmlcheatsheet.com/js/ 1/3
5/21/24, 5:34 PM JavaScript (JS) Cheat Sheet Online
Numbers and Math ∑ a += b // a = a + b (works with - * %...) onclick, onco
a && b // logical and onmousemo
var pi = 3.141; a || b // logical or
Keyboard

📆
pi.toFixed(0); // returns 3
pi.toFixed(2); // returns 3.14 - for working with money onkeydown,
pi.toPrecision(2) // returns 3.1 Dates Frame
pi.valueOf(); // returns number
Number(true); // converts to number Tue May 21 2024 17:34:24 GMT+0530 (India Standard Time) onabort, onb
Number(new Date()) // number of milliseconds since 1970 var d = new Date(); onpagehide
parseInt("3 months"); // returns the first number: 3 1716293064640 miliseconds passed since 1970 Form
parseFloat("3.5 days"); // returns 3.5 Number(d) onblur, onch
Number.MAX_VALUE // largest possible JS number
Date("2017-06-23"); // date declaration onsearch, on
Number.MIN_VALUE // smallest possible JS number
Date("2017"); // is set to Jan 01
Number.NEGATIVE_INFINITY// -Infinity Drag
Date("2017-06-23T12:00:00-09:45"); // date - time YYYY-MM-DDTHH:MM:SSZ
Number.POSITIVE_INFINITY// Infinity
Date("June 23 2017"); // long date format ondrag, ond
Math. Date("Jun 23 2017 07:45:00 GMT+0100 (Tokyo Time)"); // time zone
Clipboard
var pi = Math.PI; // 3.141592653589793 Get Times oncopy, onc
Math.round(4.4); // = 4 - rounded
var d = new Date();
Math.round(4.5); // = 5 Media
a = d.getDay(); // getting the weekday
Math.pow(2,8); // = 256 - 2 to the power of 8 onabort, onc
Math.sqrt(49); // = 7 - square root onloadeddat
getDate(); // day as a number (1-31)
Math.abs(-3.14); // = 3.14 - absolute, positive value onprogress,
getDay(); // weekday as a number (0-6)
Math.ceil(3.14); // = 4 - rounded up ontimeupdat
getFullYear(); // four digit year (yyyy)
Math.floor(3.99); // = 3 - rounded down
getHours(); // hour (0-23) Animation
Math.sin(0); // = 0 - sine
getMilliseconds(); // milliseconds (0-999)
Math.cos(Math.PI); // OTHERS: tan,atan,asin,acos, animationen
getMinutes(); // minutes (0-59)
Math.min(0, 3, -2, 2); // = -2 - the lowest value
getMonth(); // month (0-11) Miscellaneou
Math.max(0, 3, -2, 2); // = 3 - the highest value
getSeconds(); // seconds (0-59)
Math.log(1); // = 0 natural logarithm transitionend
getTime(); // milliseconds since 1970 onstorage, o
Math.exp(1); // = 2.7182pow(E,x)
Math.random(); // random number between 0 and 1 ontouchstart
Setting part of a date
Math.floor(Math.random() * 5) + 1; // random integer, from 1 to 5
var d = new Date();
Constants like Math.PI: d.setDate(d.getDate() + 7); // adds a week to a date
E, PI, SQRT2, SQRT1_2, LN2, LN10, LOG2E, Log10E Array
setDate(); // day as a number (1-31)
setFullYear(); // year (optionally month and day)
var dogs =
setHours(); // hour (0-23)
var dogs =
setMilliseconds(); // milliseconds (0-999)
Global Functions () setMinutes(); // minutes (0-59)
alert(dogs[
eval(); // executes a string as if it was script code setMonth(); // month (0-11)
dogs[0] = "
String(23); // return string from number setSeconds(); // seconds (0-59)
(23).toString(); // return string from number setTime(); // milliseconds since 1970)
for (var i
Number("23"); // return number from string console.log
decodeURI(enc); // decode URI. Result: "my page.asp" }
encodeURI(uri); // encode URI. Result: "my%page.asp" Regular Expressions \n
decodeURIComponent(enc); // decode a URI component Methods
encodeURIComponent(uri); // encode a URI component var a = str.search(/CheatSheet/i); dogs.toStri
isFinite(); // is variable a finite, legal number dogs.join("
isNaN(); // is variable an illegal number Modifiers dogs.pop();
parseFloat(); // returns floating point number of string dogs.push("
i perform case-insensitive matching
parseInt(); // parses a string and returns an integer dogs[dogs.l
g perform a global match
m perform multiline matching dogs.shift(

Ads 📣 Patterns
\ Escape character
dogs.unshif
delete dogs
dogs.splice
var animals
\d find a digit
\s find a whitespace character dogs.slice(
\b find match at beginning or end of a word dogs.sort()
n+ contains at least one n dogs.revers
n* contains zero or more occurrences of n x.sort(func
n? contains zero or one occurrences of n x.sort(func
^ Start of string highest = x
$ End of string x.sort(func
\uxxxx find the Unicode character
. Any single character concat, copy
(a|b) a or b


lastIndexOf,
(...) Group section splice, toStri
[abc] In range (a, b or c)
Errors
[0-9] any of the digits between the brackets
[^abc] Not in range
try { // block of code to try
\s White space JSON j
undefinedFunction();
a? Zero or one of a
}
a* Zero or more of a var str = '
catch(err)
a*? { // block to handle errors
Zero or more, ungreedy '{"first":"
console.log(err.message);
a+ One or more of a '{"first":"
}
a+? One or more, ungreedy '{"first":"
a{2} Exactly 2 of a
Throw error obj = JSON.
a{2,} 2 or more of a
document.wr
a{,5} "My error message";
throw Up to 5 of a// throw a text
a{2,5} 2 to 5 of a Send
a{2,5}?
Input validation 2 to 5 of a, ungreedy
[:punct:] Any punctu­ation symbol var myObj =
var x = document.getElementById("mynum").value; // get input value var myJSON
[:space:] Any space character
try {
[:blank:] Space or tab window.loca
if(x == "") throw "empty"; // error cases
if(isNaN(x)) throw "not a number"; Storing and
x = Number(x); myObj = { "
if(x > 10) throw "too high"; myJSON = JS
} localStorag
catch(err) { // if there's an error text = loca
document.write("Input is " + err); // output error obj = JSON.
console.error(err); // write the error in console document.wr
}
finally {
document.write("</br />Done"); // executed regardless of the
}

Error name values Promi


Useful Links ↵
https://htmlcheatsheet.com/js/ 2/3
5/21/24, 5:34 PM JavaScript (JS) Cheat Sheet Online
Useful Links ↵ RangeError A number is "out of range"
ReferenceError An illegal reference has occurred function su
SyntaxError A syntax error has occurred return Prom
JS cleaner Obfuscator Can I use?
TypeError A type error has occurred setTimeout
Node.js jQuery RegEx tester URIError An encodeURI() error has occurred if (type
re
}
resolve(
}, 1000);
});
}
var myPromi
myPromsise.
document.wr
return sum(
}).then(fun
}).catch(fu
console.err
});

States
pending, fulf

Properties
Promise.len

Methods
Promise.all(
Promise.res

HTML Cheat Sheet is using cookies. | PDF | Terms and Conditions, Privacy Policy
© HTMLCheatSheet.com

https://htmlcheatsheet.com/js/ 3/3

You might also like