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

JavaScript Cheatsheet

This JavaScript cheatsheet provides a comprehensive overview of key concepts including script types, variable declarations, data types, control structures, loops, string methods, array methods, operators, regular expressions, math functions, data transformation, date functions, DOM manipulation, and event handling. Each section includes descriptions and examples for clarity. It serves as a quick reference guide for JavaScript programming.

Uploaded by

Alok Kashyap
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

JavaScript Cheatsheet

This JavaScript cheatsheet provides a comprehensive overview of key concepts including script types, variable declarations, data types, control structures, loops, string methods, array methods, operators, regular expressions, math functions, data transformation, date functions, DOM manipulation, and event handling. Each section includes descriptions and examples for clarity. It serves as a quick reference guide for JavaScript programming.

Uploaded by

Alok Kashyap
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

JavaScript Cheatsheet

1. Internal and External Script


Script Description Example
Use the <script> tag and the type attribute with <script type="text/
Internal JavaScript code directly inside the HTML file. javascript"> // Code
</script>

Use the <script> tag with the src attribute to link <script src="script.js">
External
to an external JavaScript file. </script>

2. Variables
Variables Description Example
Defines a function-scoped variable that can be changed
Var var x = 10;
or redeclared.

Declares a block-scoped variable that can be changed


let let y = 20;
but not redeclared.

const Defines an immutable block-scoped variable. const z = 30;

3. JavaScript Comments
Comment Description Example
let x = 5; // This is another
Single Line Use two forward slashes //.
single line comment.

let y = 10; /* This is multiline


Use /* to start the comment
Multiline comment, but written in a single
and */ to end it.
line */.

4. Data Types
Data Type Description Example
Number Stores numeric values. let age = 30;

String Stores text enclosed in quotes. let name = “Alice”;

Boolean Stores true or false values. let isActive = true;

Object Stores key-value pairs. let user = {name: “Bob”};

Null Represents intentional absence. let result = null;

Undefined Declares an undefined variable. let data;


JavaScript Cheatsheet

5. Variables Scope
Scope Description Example
Local Variables are accessible only within the function. function test() { let x = 10; }

Global Variables are accessible anywhere in the code. let y = 20;

6. Conditional Statement
Statement Description Example
if (condition) {
Executes code block if the condition
If // Code
is true.
}

if (condition) {
// Code
Executes one block if true, and
If-else } else {
another if false.
// Code
}

switch(expression) {
case x:
Executes code blocks based on a
Switch // Code;
matching case.
break;
}

7. Loops
Type Description Example
for (let i = 0; i < 5; i++){
For Repeats code for a set number of times. // Code
}

let i = 0; while (i < 5){


Repeats code as long as the condition
While // Code
is true.
}

Executes code at least once, then do{


Do-while //code
repeats while a condition is true.
} while(i < 5);

8. Strings
Type Description Example Output
Replaces a specified pattern let text = "Hello World";
Replace() with another pattern in a console.log(text.replace( Hello Educative
string. "World", "Educative"));
JavaScript Cheatsheet
Replaces a specified pattern let text = "Hello World";
Replace() with another pattern in a console.log(text.replace( Hello Educative
string. "World", "Educative"));

Extracts parts of a string, let text = "Hello World";


substr() starting at a specified console.log(text.substr(6, World
position and length. 5));

Extracts a part of a string let text = "Hello World";


and returns it as a new console.log(text.slice(6,
slice() World
string—without modifying 11));
the original string.

let text = "Hello World,


Returns the position of the
lastIndex Welcome to the World";
last occurrence of a specified 21
Of( ) console.log(text.
pattern in a string.
lastIndexOf("World"));

let text1 = "Hello";


let text2 = "World";
concat() Joins two or more strings. Hello World
console.log(text1.
concat(" ", text2));

Searches a string for a match [ 'World', index:


let text = "Hello World";
6, input:'Hello
match() against a regular expression console.log(text.match
World', groups:
and returns the matches. (/World/));
undefined ]

Returns the character at a let text = "Hello World";


charAt() specified index (position) in console.log(text.charAt(1) e
a string. );

let text = new String


Returns the primitive ("Hello World");
valueOf() Hello World
pattern of a string object. console.log(text.valueOf());

let text = "Hello


Splits a string into an World"; ["Hello", "World"]
split()
array of substrings. console.log(text.split
(" "));

Converts a string to let text = "Hello World";


toUpper HELLO WORLD
console.log
Case() uppercase letters. (text.toUpperCase());

Converts a string to let text = "Hello World";


toLower hello world
console.log
Case() lowercase letters. (text.toLowerCase());

9. Arrays
Type Description Example Output
push() Adds new items to the end let fruits = ["Apple", ["Apple", "Banana"
of an array. "Banana"]; , "Orange"]
fruits.push("Orange");
console.log(fruits);
JavaScript Cheatsheet
let fruits = ["Apple",
Removes the last element
"Banana", "Orange"];
pop() of an array, and returns ["Apple", "Banana"]
fruits.pop();
that element. console.log(fruits);

let fruits = ["Apple",


"Banana"];
let moreFruits =
Merges two or more arrays ["Apple", "Banana",
concat() ["Orange", "Mango"];
into a new array. "Orange","Mango"]
let allFruits = fruits.
concat(moreFruits);
console.log(allFruits);

let fruits = ["Apple",


Removes the first element
"Banana", "Orange"];
shift() of an array, and returns ["Banana", "Orange"]
fruits.shift();
that element. console.log(fruits);

let fruits = ["Apple",


Reverses the order of the "Banana", "Orange"]; ["Orange", "Banana",
reverse()
elements in an array. fruits.reverse(); “Apple”]
console.log(fruits);

slice() let fruits = ["Apple",


Returns a shallow copy of a "Banana", "Orange"];
portion of an array into a let citrus = ["Banana", "Orange"]
new array object. fruits.slice(1, 3);
console.log(citrus);

Adds/removes items let fruits = ["Apple",


"Banana", "Orange"]; ["Apple", "Lemon",
to/from an array, and
splice() fruits.splice(1, 1, "Kiwi", "Orange"]
returns the removed
"Lemon", "Kiwi");
item(s). console.log(fruits);

let fruits = ["Apple",


Converts an array to a
"Banana", "Orange"];
toString() string of (comma- Apple,Banana,Orange
console.log
separated) array values. (fruits.toString());

Returns the array itself let fruits = ["Apple",


"Banana", "Orange"]; ["Apple", "Banana",
valueOf() (similar to the toString()
console.log "Orange"]
method for arrays).
(fruits.valueOf());

let fruits = ["Apple",


Returns the first index at
"Banana", "Orange"];
the position where a given
indexOf() console.log 1
element can be found in (fruits.indexOf
the array. ("Banana"));

let fruits = ["Apple",


Returns the last index a "Banana", "Orange",
lastIndex the position where a given "Banana"];
3
Of() element can be found in console.log
the array. (fruits.lastIndexOf
("Banana"));

let fruits = ["Apple",


Joins all elements of an "Banana", "Orange"]; Apple - Banana -
join()
array into a string. console.log Orange
(fruits.join(" - "));
JavaScript Cheatsheet
Sorts the elements of an let fruits = ["Banana",
array in place and returns "Apple", "Orange"]; ["Apple", "Banana",
sort()
the sorted array. fruits.sort(); "Orange"]
console.log(fruits);

10. Operators
Type Operator Example Output
AND (&) 5&1 1

OR (|) 5|1 5

XOR (^) 5^1 4


Bitwise
NOT (~) ~5 r -6

Left shift (<<) 5 << 1 10

Right shift (>>) 5 >> 1 2

Assignment (=) x=5

Add and assign (+=) x += 5 (same as x = x + 5)

Assignment Subtract and assign (-=) x -= 5 (same as x = x - 5)

Multiply and assign (*=) x *= 5 (same as x = x * 5)

Divide and assign (/=) x /= 5 (same as x = x / 5)

Equal (==) 5 == 1 true

Strict Equal (===) 5 === ‘5’ false

Comparison Not Equal (!=) 5 != 5 false

Greater Than (>) 5>3 true

Less Than (<) 5<3 false

Addition (+) 5+3 8

Subtraction (-) 5-3 2

Multiplication (*) 5*3 15

Arithmetic Division (/) 5/3 1.6667

Modulus (%) 5%3 2

Increment (++) ++x increases x by 1

Decrement (--) --x decreases x by 1

AND (&&) true && false false

Logical OR (||) true || false true

NOT (!) !true false


JavaScript Cheatsheet

11. Regular Expressions


Expression Description Example Output
[0-9] It matches any digit from 0 to 9. /[0-9]/.test(’5’) true

Matches any character within the


[abc] /[abc]/.test('b') true
brackets (a, b, or c).

(x|y) It matches either x or y. /(x|y)/.test('y') true

12. Math Functions


Function Description Example Output
valueOf() Returns the primitive value of a var num = 123;
123
specified object. num.valueOf();

toString() Converts a number or object to var num = 123;


123
a string. num.toString();

toPrecision Formats a number to a specified var num = 123.456;


123.5
() length. num.toPrecision(4);

toExponential Converts a number to exponential var num = 123.456;


1.23e+2
() notation. num.toPrecision(2);

toFixed() Formats a number using fixed- var num = 123.456;


123.46
point notation. num.toFixed(2);

13. Data Transformation


Function Description Example Output
Creates a new array by applying var arr = [1, 2, 3];
map() a function to each element arr.map(x => x * 2); [2, 4, 6]
of the original array.

var arr = [1, 2, 3, 4];


Creates a new array with elements
filter() arr.filter(x => x % 2 [2, 4]
that pass a specified test.
=== 0);

Reduces an array to a single value var arr = [1, 2, 3, 4];


reduce() by applying a function to each arr.reduce((sum, x) => 10
element. sum + x, 0);

14. Date
Function Description Example Output
Returns the minutes (0–59) of a var date = new Date();
getMinutes() date.getMinutes(); (e.g., 45)
specified date and time.
JavaScript Cheatsheet
Returns the day of the month var date = new Date();
getDate() date.getDate(); (e.g., 28)
(1–31) for a specified date.

Returns the number of milli- var date = new Date();


(e.g.,
getTime() seconds from a given date, date.getTime();
1625914871267)
e.g., January 1, 1970.

Returns the full year (4 digits) of var date = new Date();


getFullYear() 2024
a specified date. date.getFullYear();

Returns the day of the week var date = new Date(); (e.g., 2 for
getDay() Tuesday)
(0–6) for a specified date. date.getDay();

Parses a date string and returns


Date.parse
parse() the number of milliseconds (e.g., -14182920000
("July 20, 1969");
January 1, 1970).

Parses a date string and returns


var date = new Date(); (date set to
setDate() the number of milliseconds
date.setDate(15); the 15th)
(e.g., January 1, 1970).

var date = new Date(); (date set to


Sets a date and time by adding
setTime() date.setTime corresponding
milliseconds (e.g., January 1, 1970). (1625914871267); date and time)

15. Document Object Model


Function Description Example
var parent = document.
Adds a new child node to the getElementById("parent");
appendChild()
end of a parent node. var child = document.createElement("div");
parent.appendChild(child);

var original = document.


getElementById("original");
cloneNode() Creates a copy of a node.
var clone = original.cloneNode(true);
document.body.appendChild(clone);

var element = document.


hasAttributes Returns true if the node has
getElementById("element");
() any attributes. var hasAttr = element.hasAttributes();

var parent = document.


getElementById("parent");
Removes a child node from
removeChild() var child = document.
a parent node.
getElementById("child");
parent.removeChild(child);

var element = document.


Returns the value of a
getElementById("element");
getAttribute() specified attribute on an
var attrValue = element.
element. getAttribute("class");

Returns a live HTML


getElements var elements = document.
collection of elements with
ByTagName() getElementsByTagName("p");
the specified tag name.
JavaScript Cheatsheet
isEqualNode() Checks if the two nodes are var node1 = document.
equal. getElementById("node1");
var node2 = document.
getElementById("node2");
var isEqual = node1.isEqualNode(node2);

16. Events
Model Description Example
Triggers a function when an <button onclick="alert('Button
onclick()
element is clicked. clicked!')">Click me</button>

Triggers a function when a <input type="text" onkeyup="


onkeyup()
key is released. console.log('Key released!')" />

Triggers a function when the <div onmouseover="console.log


onmouseover ('Mouse over!')">Hover over me
mouse pointer is over an
()
element. </div>

Triggers a function when the <div onmouseout="console.log


onmouseout() mouse pointer leaves an ('Mouse out!')">Move out of me
element. </div>

<input type="text" onchange=


Triggers a function when the
onchange() "console.log('Value changed!')"
value of an element changes.
/>

Triggers a function when the <input type="text" onchange=


onload() page or an image is fully "console.log('Value changed!')"
loaded. />

<input type="text" onfocus=


Triggers a function when an
onfocus() "console.log('Input focused!')"
element gets focus.
/>

<input type="text" onblur=


Triggers a function when an
onblur() "console.log('Input lost focus!'
element loses focus.
)" />

<form onsubmit="console.log
('Form submitted!')">
Triggers a function when a
onsubmit() <input type="submit" value=
form is submitted.
"Submit">
</form>

<div draggable="true"
Triggers a function when an ondrag="console.log
ondrag() ('Element dragged!')
element is dragged.
">Drag me</div>

Triggers a function when the <input type="text" oninput=


oninput() value of an element changes "console.log('Input value
while typing. changed!')" />
JavaScript Cheatsheet

17. Error
Model Description Example
try {
Defines a block of code to
Try // Code to try
test for errors.
}

catch (error) {
Defines a block of code to
catch // Code to handle error
handle any errors
}

throw new Error


throw Creates a custom error.
('This is an error!');

finally {
Executes code after try
// Code to execute after try
finally and catch, regardless of the
and catch
result.
}

You might also like