JavaScript is a high-level, interpreted programming language that is widely used for web development. This cheatsheet covers essential JavaScript concepts, methods, and examples to help you write efficient code.
For more advanced JavaScript topics, check out my JavaScript tutorial.
JavaScript Basics
Set of JavaScript basic syntax to add, execute and write basic programming paradigms in Javascript
On Page Script
<script type="text/javascript">
//JS code goes here
</script>External JS File
<script src="filename.js"></script>Functions
function functionName() {
// code to be executed
}DOM Element
const element = document.getElementById("elementID");Console Methods
| Method | Description | Example |
|---|---|---|
console.log() | Outputs a message to the console | console.log("Hello World") |
console.table() | Displays tabular data as a table | console.table([{a:1, b:2}, {a:3}]) |
console.error() | Outputs an error message | console.error("This is an error") |
console.warn() | Outputs a warning message | console.warn("This is a warning") |
console.clear() | Clears the console | console.clear() |
console.time() | Starts a timer (use with timeEnd) | console.time("Timer") |
console.timeEnd() | Ends a timer and logs result | console.timeEnd("Timer") |
console.count() | Logs number of times this has been called | console.count("Counter") |
Conditional Statements
Conditional statements are used to perform operations based on some conditions.
If Statement
if (condition) {
// code to be executed
}If-Else Statement
if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}If-Else-If Statement
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if neither condition is true
}Switch Statement
switch (expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}Loops
Loops are used to execute the same block of code again and again, as long as a certain condition is met.
For Loop
for (initialization; condition; increment / decrement) {
// code to be executed
}Example:
for (let i = 0; i < 5; i++) {
text += "Iteration number: " + i + "<br />";
}For-Of Loop
for (const item of iterable) {
// code to be executed for each item
}For-In Loop
for (const key in object) {
// code to be executed for each key in the object
}While Loop
while (condition) {
// code to be executed
}Do-While Loop
do {
// code to be executed
} while (condition);Strings
The string is a sequence of characters that is used for storing and managing text data.
const str1 = "A string primitive";
const str2 = "Also a string primitive";
const str3 = `Yet another string primitive`;
const str4 = new String("A String object");String Methods
| Method | Description | Example | Output |
|---|---|---|---|
charAt() | Returns character at given index | "Hello".charAt(1) | e |
concat() | Joins two or more strings | "Hello".concat(" World") | Hello World |
endsWith() | Checks if string ends with specified substring | "hello".endsWith("lo") | true |
includes() | Checks if string contains substring | "hello".includes("he") | true |
indexOf() | Finds index of substring | "Hello".indexOf("l") | 2 |
localeCompare() | Compares two strings in the current locale | "a".localeCompare("b") | -1 |
match() | Matches regex | "abc123".match(/\\d+/) | ["123"] |
padEnd() | Pads string from the end | "5".padEnd(3, "0") | "500" |
padStart() | Pads string from the start | "5".padStart(3, "0") | "005" |
repeat() | Returns string repeated given times | "ha".repeat(3) | "hahaha" |
replace() | Replaces specified value in string | "Hello".replace("H","J") | "Jello" |
search() | Searches string for match (regex) | "abc123".search(/\\d+/) | 3 |
slice() | Extracts section of string | "Hello".slice(1,4) | "ell" |
split() | Splits string into an array | "a,b,c".split(",") | ["a", "b", "c"] |
startsWith() | Checks if string starts with specified substring | "hello".startsWith("he") | true |
substring() | Returns part of the string between indexes | "Hello".substring(1,4) | "ell" |
toLowerCase() | Converts string to lowercase | "HELLO".toLowerCase() | "hello" |
toString() | Converts to string | 123.toString() | "123" |
toUpperCase() | Converts string to uppercase | "hello".toUpperCase() | "HELLO" |
trim() | Removes whitespace from both ends | " hi ".trim() | "hi" |
valueOf() | Returns primitive value of the string | "hello".valueOf() | "hello" |
See more on MDN Web Docs.
Arrays
Arrays are used to store multiple values in a single variable.
const arr1 = [1, 2, 3];
const arr2 = ["a", "b", "c"];
const arr3 = [true, false, true];
const arr4 = new Array(5);Array Methods
| Method | Description | Example | Output |
|---|---|---|---|
concat() | Joins two or more arrays | [1, 2].concat([3, 4]) | [1, 2, 3, 4] |
push() | Adds new elements to the end of an array | [1, 2].push(3) | [1, 2, 3] |
pop() | Removes the last element from an array | [1, 2, 3].pop() | [1, 2] |
shift() | Removes the first element from an array | [1, 2, 3].shift() | [2, 3] |
unshift() | Adds new elements to the beginning of an array | [1, 2].unshift(0) | [0, 1, 2] |
splice() | Adds or removes elements from an array | [1, 2, 3].splice(1, 1, 4) | [1, 4, 3] |
slice() | Returns a new array from a specified index | [1, 2, 3].slice(1, 2) | [2] |
join() | Joins all elements of an array into a string | [1, 2, 3].join(", ") | "1, 2, 3" |
sort() | Sorts the elements of an array | [3, 1, 2].sort() | [1, 2, 3] |
toString() | Converts an array to a string | [1, 2, 3].toString() | "1,2,3" |
valueOf() | Returns the primitive value of an array | [1, 2, 3].valueOf() | [1, 2, 3] |
indexOf() | Returns the index of the first occurrence of a specified element in an array | [1, 2, 3].indexOf(2) | 1 |
forEach() | Executes a provided function once for each array element | [1, 2, 3].forEach((num) => console.log(num)) | 1 2 3 |
See more on MDN Web Docs.
Number Methods
JS math and number objects provide several constant and methods to perform mathematical operations.
| Method | Description | Example | Output |
|---|---|---|---|
isNaN() | Checks if a value is NaN (Not-a-Number) | isNaN("Hello") | true |
isFinite() | Checks if a value is a finite number | isFinite(123) | true |
parseFloat() | Parses a string and returns a floating-point number | parseFloat("3.14") | 3.14 |
parseInt() | Parses a string and returns an integer | parseInt("42") | 42 |
toExponential() | Converts a number to its exponential form | (123456).toExponential(2) | "1.23e+5" |
toFixed() | Formats a number using fixed-point notation | (123.456).toFixed(2) | "123.46" |
toPrecision() | Formats a number to a specified length | (123.456).toPrecision(4) | "123.5" |
toString() | Converts a number to a string | (123).toString() | "123" |
valueOf() | Returns the primitive value of a number | (123).valueOf() | 123 |
See more on MDN Web Docs.
Math Methods
Math object provides several constants and methods to perform mathematical operations.
| Method | Description | Example | Output |
|---|---|---|---|
Math.PI | Returns the value of PI | Math.PI | 3.141592653589793 |
Math.ceil() | Rounds a number up to the nearest integer | Math.ceil(4.7) | 5 |
Math.floor() | Rounds a number down to the nearest integer | Math.floor(4.7) | 4 |
Math.round() | Rounds a number to the nearest integer | Math.round(4.7) | 5 |
Math.max() | Returns the largest of zero or more numbers | Math.max(4, 7, 2) | 7 |
Math.min() | Returns the smallest of zero or more numbers | Math.min(4, 7, 2) | 2 |
Math.exp() | Returns E raised to the power of a number | Math.exp(1) | 2.718281828459045 |
Math.log() | Returns the natural logarithm of a number | Math.log(10) | 2.302585092994046 |
Math.pow() | Returns the value of a number raised to a power | Math.pow(2, 3) | 8 |
Math.random() | Returns a random number between 0 and 1 | Math.random() | 0.123456789 |
Math.sqrt() | Returns the square root of a number | Math.sqrt(16) | 4 |
Math.abs() | Returns the absolute value of a number | Math.abs(-5) | 5 |
Math.sin() | Returns the sine of a number | Math.sin(0) | 0 |
Math.cos() | Returns the cosine of a number | Math.cos(0) | 1 |
Math.tan() | Returns the tangent of a number | Math.tan(0) | 0 |
See more on MDN Web Docs.
Date Methods
Date object is used to get the year, month and day. It has methods to get and set day, month, year, hour, minute, and seconds.
let date = new Date();| Method | Description | Example | Output |
|---|---|---|---|
getDate() | Returns the day of the month (1-31) | date.getDate() | 25 |
getDay() | Returns the day of the week (0-6) | date.getDay() | 2 |
getFullYear() | Returns the four-digit year | date.getFullYear() | 2024 |
getMonth() | Returns the month (0-11) | date.getMonth() | 8 |
getHours() | Returns the hour (0-23) | date.getHours() | 14 |
getMinutes() | Returns the minutes (0-59) | date.getMinutes() | 30 |
getSeconds() | Returns the seconds (0-59) | date.getSeconds() | 45 |
getMilliseconds() | Returns the milliseconds (0-999) | date.getMilliseconds() | 123 |
getTime() | Returns the number of milliseconds since Jan 1, 1970 | date.getTime() | 1727251200000 |
See more on MDN Web Docs.
Mouse Events
Any change in the state of an object is referred to as an Event. With the help of JS, you can handle events, i.e., how any specific HTML tag will work when the user does something.
const element = document.getElementById("myBtn");| Event | Description | Example |
|---|---|---|
click | Occurs when the user clicks on an element | element.addEventListener("click", callback) |
contextmenu | Occurs when the user right-clicks on an element to open a context menu | element.addEventListener("contextmenu", callback) |
dblclick | Occurs when the user double-clicks on an element | element.addEventListener("dblclick", callback) |
mouseenter | Occurs when the mouse pointer is moved onto an element | element.addEventListener("mouseenter", callback) |
mouseleave | Occurs when the mouse pointer is moved out of an element | element.addEventListener("mouseleave", callback) |
mouseover | Occurs when the mouse pointer is moved over an element | element.addEventListener("mouseover", callback) |
mouseout | Occurs when the mouse pointer is moved out of an element | element.addEventListener("mouseout", callback) |
mousemove | Occurs when the mouse pointer is moving while it is over an element | element.addEventListener("mousemove", callback) |
Keyboard Events
Keyboard events are used to handle the user's keyboard input.
const element = document.getElementById("myInput");| Event | Description | Example |
|---|---|---|
keydown | Occurs when the user is pressing a key | element.addEventListener("keydown", callback) |
keypress | Occurs when the user presses a key | element.addEventListener("keypress", callback) |
keyup | Occurs when the user releases a key | element.addEventListener("keyup", callback) |
Errors
Errors are thrown by the compiler or interpreter whenever they find any fault in the code, and it can be of any type like syntax error, run-time error, logical error, etc. JS provides some functions to handle the errors.
try-catch
try {
// code to be executed
} catch (error) {
// code to be executed if an error occurs
}throw
throw new Error("An error occurred");Window Methods
Methods that are available from the window object
| Method | Description | Example |
|---|---|---|
alert() | Displays an alert box with a message and an OK button | window.alert("Hello World!") |
confirm() | Displays a dialog box with a message and OK/Cancel buttons | window.confirm("Press a button!") |
prompt() | Displays a dialog box that prompts the visitor for input | window.prompt("Please enter your name", "John Doe") |
blur() | Removes focus from the current window | window.blur() |
focus() | Sets focus to the current window | window.focus() |
setInterval() | Calls a function at specified intervals (in milliseconds) | setInterval(() => { /* Code */ }, 1000) |
setTimeout() | Calls a function after a specified delay (in milliseconds) | setTimeout(() => { /* Code */ }, 1000) |
open() | Opens a new browser window | window.open("https://www.example.com", "_blank") |
close() | Closes the current window | window.close() |
scrollBy() | Scrolls the document by the specified number of pixels | window.scrollBy(0, 100) |
scrollTo() | Scrolls the document to the specified coordinates | window.scrollTo(0, 100) |
clearInterval() | Clears a timer set with setInterval() | clearInterval(timer) |
clearTimeout() | Clears a timer set with setTimeout() | clearTimeout(timer) |
stop() | Stops further resource loading | window.stop() |
DOM Manipulation Methods
The browser creates a Document Object Model (DOM) whenever a web page is loaded. Using the HTML DOM, you can access and modify all elements of the HTML document.
Query/Get Elements
| Method | Description | Example |
|---|---|---|
querySelector() | Returns first element matching a CSS selector | document.querySelector("p") |
querySelectorAll() | Returns all elements matching CSS selector(s) | document.querySelectorAll("p") |
getElementById() | Returns element with the specified ID | document.getElementById("example") |
getElementsByClassName() | Returns collection of elements with the specified class | document.getElementsByClassName("box") |
getElementsByTagName() | Returns collection of elements with the specified tag | document.getElementsByTagName("div") |
Creating & Modifying Elements
| Method | Description | Example |
|---|---|---|
createElement() | Creates a new element | document.createElement("p") |
createTextNode() | Creates a text node | document.createTextNode("Hello World!") |
appendChild() | Appends a node as a child | parent.appendChild(child) |
removeChild() | Removes a child node | parent.removeChild(child) |
replaceChild() | Replaces a child node | parent.replaceChild(newChild, oldChild) |
insertBefore() | Inserts a node before another node | parent.insertBefore(newNode, referenceNode) |
setAttribute() | Sets attribute on element | element.setAttribute("class", "active") |
getAttribute() | Gets attribute value | element.getAttribute("id") |
removeAttribute() | Removes attribute from element | element.removeAttribute("disabled") |
DOM Navigation
| Method | Description | Example Usage |
|---|---|---|
parentNode | Returns the parent node of an element | element.parentNode |
childNodes | Returns collection of child nodes | element.childNodes |
firstChild | Returns the first child node | element.firstChild |
lastChild | Returns the last child node | element.lastChild |
nextSibling | Returns the next node at the same level | element.nextSibling |
previousSibling | Returns the previous node at the same level | element.previousSibling |
children | Returns collection of element's children | element.children |
firstElementChild | Returns the first child element | element.firstElementChild |
lastElementChild | Returns the last child element | element.lastElementChild |
Conclusion
This cheatsheet covers essential JavaScript concepts, methods, and examples to help you write efficient code. JavaScript is a high-level, interpreted programming language that is widely used for web development. It is a versatile language that can be used for both client-side and server-side development. By mastering JavaScript, you can build interactive web applications and create dynamic content on your website.
Written by
Shyam Verma
At
Sep 25, 2024
Last updated on
Read time
7 min
Tags