0% found this document useful (0 votes)
2 views3 pages

JavaScript (JS) Cheat Sheet With Examples

The document is a comprehensive JavaScript (JS) cheat sheet covering various topics including basics, loops, functions, data types, operators, and event handling. It provides code snippets and examples for each concept, making it a useful reference for both beginners and experienced developers. Additionally, it includes information on regular expressions, error handling, and global functions.
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)
2 views3 pages

JavaScript (JS) Cheat Sheet With Examples

The document is a comprehensive JavaScript (JS) cheat sheet covering various topics including basics, loops, functions, data types, operators, and event handling. It provides code snippets and examples for each concept, making it a useful reference for both beginners and experienced developers. Additionally, it includes information on regular expressions, error handling, and global functions.
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

5/12/26, 12:57 PM JavaScript (JS) Cheat Sheet Online

Hide comments

JS Cheat Sheet
Basics ➤ Loops

Ads 📣 On page script


<script type="text/javascript"> ...
For Loop
for (var i
</script> document.w
}
Include external JS file var sum =
<script src="[Link]"></script> for (var i
sum + = a[
Delay - 1 second timeout }
html = "";
setTimeout(function () {
for (var i
}, 1000); html += "<
}
Functions
While Loop
function addNumbers(a, b) {
return a + b; ; var i = 1;
while (i <
}
x = addNumbers(1, 2); i *= 2;
document.w
}
Edit DOM element
[Link]("elementID").innerHTML = "Hello World!"; Do While Lo
var i = 1;
Output do {
If - Else ⇵ [Link](a); // write to the browser console i *= 2;
[Link](a); // write to the HTML document.w
if ((age >= 14) && (age < 19)) { // logical condition
alert(a); // output in an alert box } while (i
status = "Eligible."; // executed if condition is true
confirm("Really?"); // yes/no dialog, returns true/false depending
} else { // else block is optional
prompt("Your age?","0"); // input dialog. Second argument is the initial Break
status = "Not eligible."; // executed if condition is false
for (var i
} Comments if (i == 5
Switch Statement /* Multi line document.w
comment */ }
switch (new Date().getDay()) { // input is current day
// One line
case 6: // if (day == 6) Continue
text = "Saturday";
for (var i
break;
case 0: // if (day == 0) Variables x if (i == 5
document.w
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";
var e = [2,3,5,8];
//
//
= "33"
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 [Link] + " " + [Link]; a = b * (c / d); // multiplication, division
} x = 100 % 48; // modulo. 100 / 48 remainder = 4
}; a++; b--; // postfix increment and decrement
[Link] = 19; // setting value
student[age]++; // incrementing Bitwise operators
name = [Link](); // 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)
>> right shift 5 >> 1 (0101 >> 1) 2 (10)
var abc = "abcdefghijklmnopqrstuvwxyz";
>>> zero fill right shift 5 >>> 1 (0101 >>> 1) 2 (10)
var esc = 'I don\'t \n know'; // \n new line
var len = [Link]; // string length Arithmetic
[Link]("lmno"); // find substring, -1 if doesn't contain
a * (b + c) // grouping
[Link]("lmno"); // last occurance
[Link] // member
[Link](3, 6); // cuts out "def", negative values count fr
person[age] // member
[Link]("abc","123"); // find and replace, takes regular expressi
!(a == b) // logical not
[Link](); // convert to upper case
a != b // not equal
[Link](); // convert to lower case
typeof a // type (number, object, function...)
[Link](" ", str2); // abc + " " + str2
x << 2 x >> 3 // minary shifting
[Link](2); // character at index: "c"
a = b // assignment
abc[2]; // unsafe, abc[2] = "C" doesn't work
a == b // equals
[Link](2); // character code at index: "c" -> 99
a != b // unequal Event
[Link] 1/3
5/12/26, 12:57 PM JavaScript (JS) Cheat Sheet Online
[Link](","); // splitting a string on commas gives an ar a === b // strict equal
<button on
[Link](""); // splitting on characters a !== b // strict unequal
Click here
[Link](16); // number to hex(16), octal (8) or binary ( a < b a > b // less and greater than
</button>
a <= b a >= b // less or equal, greater or eq
a += b // a = a + b (works with - * %...)
Numbers and Math ∑ a && b // logical and
Mouse
onclick, onc
a || b // logical or
var pi = 3.141; onmousemo
[Link](0); // returns 3
Keyboard
[Link](2); // returns 3.14 - for working with money
[Link](2) // returns 3.1 Dates 📆 onkeydown
[Link](); // returns number
Tue May 12 2026 11:51:54 GMT+0530 (India Standard Time) Frame
Number(true); // converts to number
Number(new Date()) // number of milliseconds since 1970 var d = new Date(); onabort, on
parseInt("3 months"); // returns the first number: 3 onresize, on
1778566914558 miliseconds passed since 1970
parseFloat("3.5 days"); // returns 3.5 Number(d) Form
Number.MAX_VALUE // largest possible JS number
Date("2017-06-23"); // date declaration onblur, onch
Number.MIN_VALUE // smallest possible JS number
Date("2017"); // is set to Jan 01 onsearch, o
Number.NEGATIVE_INFINITY// -Infinity Date("2017-06-23T12:00:00-09:45"); // date - time YYYY-MM-DDTHH:MM:SSZ
Number.POSITIVE_INFINITY// Infinity Drag
Date("June 23 2017"); // long date format
Date("Jun 23 2017 07:45:00 GMT+0100 (Tokyo Time)"); // time zone ondrag, ond
Math.
var pi = [Link]; // 3.141592653589793 Get Times Clipboard
[Link](4.4); // = 4 - rounded
var d = new Date(); oncopy, onc
[Link](4.5); // = 5 a = [Link](); // getting the weekday
[Link](2,8); // = 256 - 2 to the power of 8 Media
[Link](49); // = 7 - square root onabort, on
getDate(); // day as a number (1-31)
[Link](-3.14); // = 3.14 - absolute, positive value getDay(); // weekday as a number (0-6) onloadedda
[Link](3.14); // = 4 - rounded up onprogress
getFullYear(); // four digit year (yyyy)
[Link](3.99); // = 3 - rounded down ontimeupda
getHours(); // hour (0-23)
[Link](0); // = 0 - sine getMilliseconds(); // milliseconds (0-999)
[Link]([Link]); // OTHERS: tan,atan,asin,acos, Animation
getMinutes(); // minutes (0-59)
[Link](0, 3, -2, 2); // = -2 - the lowest value getMonth(); // month (0-11) animationen
[Link](0, 3, -2, 2); // = 3 - the highest value
getSeconds(); // seconds (0-59) Miscellaneo
[Link](1); // = 0 natural logarithm getTime(); // milliseconds since 1970
[Link](1); // = 2.7182pow(E,x) transitionen
[Link](); // random number between 0 and 1 Setting part of a date onstorage,
[Link]([Link]() * 5) + 1; // random integer, from 1 to 5 ontouchstar
var d = new Date();
[Link]([Link]() + 7); // adds a week to a date
Constants like [Link]:
E, PI, SQRT2, SQRT1_2, LN2, LN10, LOG2E, Log10E setDate(); // day as a number (1-31) Array
setFullYear(); // year (optionally month and day)
setHours(); // hour (0-23) var dogs =
var dogs =
Global Functions () setMilliseconds();
setMinutes();
//
//
milliseconds (0-999)
minutes (0-59)
setMonth(); // month (0-11) alert(dogs
eval(); // executes a string as if it was script code dogs[0] =
setSeconds(); // seconds (0-59)
String(23); // return string from number
setTime(); // milliseconds since 1970)
(23).toString(); // return string from number for (var i
Number("23"); // return number from string [Link]
decodeURI(enc); // decode URI. Result: "my [Link]" }
encodeURI(uri); // encode URI. Result: "my%[Link]" Regular Expressions \n
decodeURIComponent(enc); // decode a URI component Methods
encodeURIComponent(uri); // encode a URI component var a = [Link](/CheatSheet/i); [Link]
isFinite(); // is variable a finite, legal number [Link](
isNaN(); // is variable an illegal number Modifiers [Link]()
parseFloat(); // returns floating point number of string [Link](
i perform case-insensitive matching
parseInt(); // parses a string and returns an integer g perform a global match dogs[dogs.
m perform multiline matching [Link]
[Link]
Patterns
Ads 📣 \ Escape character
delete dog
[Link]
\d find a digit var animal
\s find a whitespace character [Link]
\b find match at beginning or end of a word [Link](
n+ contains at least one n [Link]
n* contains zero or more occurrences of n [Link](fun
n? contains zero or one occurrences of n [Link](fun
^ Start of string
highest =
$ End of string
[Link](fun
\uxxxx find the Unicode character
. Any single character
(a|b) a or b concat, cop
(...) Group section lastIndexOf
splice, toStr
Errors ⚠
[abc]
[0-9]
In range (a, b or c)
any of the digits between the brackets
[^abc] Not in range
try { // block of code to try
\s White space
undefinedFunction();
a? Zero or one of a
JSON j
}
a* Zero or more of a
catch(err) { // block to handle errors var str =
a*? Zero or more, ungreedy
[Link]([Link]); '{"first":
a+ One or more of a
} '{"first":
a+? One or more, ungreedy
a{2} Exactly 2 of a '{"first":
Throw
a{2,} error 2 or more of a obj = JSON
a{,5} "My error message";
throw Up to 5 of a// throw a text document.w
a{2,5} 2 to 5 of a
a{2,5}? 2 to 5 of a, ungreedy Send
Input validation
[:punct:] Any punctu­ation symbol var myObj
var x = [Link]("mynum").value; // get input value
[:space:] Any space character var myJSON
try {
[:blank:] Space or tab [Link]
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 = J
}
localStora
catch(err) { // if there's an error
text = loc
[Link]("Input is " + err); // output error obj = JSON
[Link](err); // write the error in console document.w
}

[Link] 2/3
5/12/26, 12:57 PM JavaScript (JS) Cheat Sheet Online
finally {
[Link]("</br />Done"); // executed regardless of the t
} Promi
Useful Links ↵ Error name values
RangeError A number is "out of range"
function s
return Pro
ReferenceError An illegal reference has occurred setTimeou
JS cleaner Obfuscator Can I use? SyntaxError A syntax error has occurred if (typ
[Link] jQuery RegEx tester TypeError A type error has occurred r
URIError An encodeURI() error has occurred }
resolve
}, 1000);
});
}
var myProm
myPromsise
document.w
return sum
}).then(fu
}).catch(f
[Link]
});

States
pending, fu

Properties
[Link]

Methods
[Link](
[Link]

HTML Cheat Sheet is using cookies. | PDF | Terms and Conditions, Privacy Policy
© [Link]

[Link] 3/3

You might also like