loader

Loading

CoderrShyam logo

CoderrShyam

  • Home
  • About
  • Contact
  • Blog
  • Tutorials
    LoginSignup

JavaScript Cheatsheet

JavaScript Cheatsheet:- Quick guide to essential JS concepts and syntax for dynamic web development.

Back

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

MethodDescriptionExample
console.log()Outputs a message to the consoleconsole.log("Hello World")
console.table()Displays tabular data as a tableconsole.table([{a:1, b:2}, {a:3}])
console.error()Outputs an error messageconsole.error("This is an error")
console.warn()Outputs a warning messageconsole.warn("This is a warning")
console.clear()Clears the consoleconsole.clear()
console.time()Starts a timer (use with timeEnd)console.time("Timer")
console.timeEnd()Ends a timer and logs resultconsole.timeEnd("Timer")
console.count()Logs number of times this has been calledconsole.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

MethodDescriptionExampleOutput
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 string123.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

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

MethodDescriptionExampleOutput
isNaN()Checks if a value is NaN (Not-a-Number)isNaN("Hello")true
isFinite()Checks if a value is a finite numberisFinite(123)true
parseFloat()Parses a string and returns a floating-point numberparseFloat("3.14")3.14
parseInt()Parses a string and returns an integerparseInt("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.

MethodDescriptionExampleOutput
Math.PIReturns the value of PIMath.PI3.141592653589793
Math.ceil()Rounds a number up to the nearest integerMath.ceil(4.7)5
Math.floor()Rounds a number down to the nearest integerMath.floor(4.7)4
Math.round()Rounds a number to the nearest integerMath.round(4.7)5
Math.max()Returns the largest of zero or more numbersMath.max(4, 7, 2)7
Math.min()Returns the smallest of zero or more numbersMath.min(4, 7, 2)2
Math.exp()Returns E raised to the power of a numberMath.exp(1)2.718281828459045
Math.log()Returns the natural logarithm of a numberMath.log(10)2.302585092994046
Math.pow()Returns the value of a number raised to a powerMath.pow(2, 3)8
Math.random()Returns a random number between 0 and 1Math.random()0.123456789
Math.sqrt()Returns the square root of a numberMath.sqrt(16)4
Math.abs()Returns the absolute value of a numberMath.abs(-5)5
Math.sin()Returns the sine of a numberMath.sin(0)0
Math.cos()Returns the cosine of a numberMath.cos(0)1
Math.tan()Returns the tangent of a numberMath.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();
MethodDescriptionExampleOutput
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 yeardate.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, 1970date.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");
EventDescriptionExample
clickOccurs when the user clicks on an elementelement.addEventListener("click", callback)
contextmenuOccurs when the user right-clicks on an element to open a context menuelement.addEventListener("contextmenu", callback)
dblclickOccurs when the user double-clicks on an elementelement.addEventListener("dblclick", callback)
mouseenterOccurs when the mouse pointer is moved onto an elementelement.addEventListener("mouseenter", callback)
mouseleaveOccurs when the mouse pointer is moved out of an elementelement.addEventListener("mouseleave", callback)
mouseoverOccurs when the mouse pointer is moved over an elementelement.addEventListener("mouseover", callback)
mouseoutOccurs when the mouse pointer is moved out of an elementelement.addEventListener("mouseout", callback)
mousemoveOccurs when the mouse pointer is moving while it is over an elementelement.addEventListener("mousemove", callback)

Keyboard Events

Keyboard events are used to handle the user's keyboard input.

const element = document.getElementById("myInput");
EventDescriptionExample
keydownOccurs when the user is pressing a keyelement.addEventListener("keydown", callback)
keypressOccurs when the user presses a keyelement.addEventListener("keypress", callback)
keyupOccurs when the user releases a keyelement.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

MethodDescriptionExample
alert()Displays an alert box with a message and an OK buttonwindow.alert("Hello World!")
confirm()Displays a dialog box with a message and OK/Cancel buttonswindow.confirm("Press a button!")
prompt()Displays a dialog box that prompts the visitor for inputwindow.prompt("Please enter your name", "John Doe")
blur()Removes focus from the current windowwindow.blur()
focus()Sets focus to the current windowwindow.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 windowwindow.open("https://www.example.com", "_blank")
close()Closes the current windowwindow.close()
scrollBy()Scrolls the document by the specified number of pixelswindow.scrollBy(0, 100)
scrollTo()Scrolls the document to the specified coordinateswindow.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 loadingwindow.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

MethodDescriptionExample
querySelector()Returns first element matching a CSS selectordocument.querySelector("p")
querySelectorAll()Returns all elements matching CSS selector(s)document.querySelectorAll("p")
getElementById()Returns element with the specified IDdocument.getElementById("example")
getElementsByClassName()Returns collection of elements with the specified classdocument.getElementsByClassName("box")
getElementsByTagName()Returns collection of elements with the specified tagdocument.getElementsByTagName("div")

Creating & Modifying Elements

MethodDescriptionExample
createElement()Creates a new elementdocument.createElement("p")
createTextNode()Creates a text nodedocument.createTextNode("Hello World!")
appendChild()Appends a node as a childparent.appendChild(child)
removeChild()Removes a child nodeparent.removeChild(child)
replaceChild()Replaces a child nodeparent.replaceChild(newChild, oldChild)
insertBefore()Inserts a node before another nodeparent.insertBefore(newNode, referenceNode)
setAttribute()Sets attribute on elementelement.setAttribute("class", "active")
getAttribute()Gets attribute valueelement.getAttribute("id")
removeAttribute()Removes attribute from elementelement.removeAttribute("disabled")

DOM Navigation

MethodDescriptionExample Usage
parentNodeReturns the parent node of an elementelement.parentNode
childNodesReturns collection of child nodeselement.childNodes
firstChildReturns the first child nodeelement.firstChild
lastChildReturns the last child nodeelement.lastChild
nextSiblingReturns the next node at the same levelelement.nextSibling
previousSiblingReturns the previous node at the same levelelement.previousSibling
childrenReturns collection of element's childrenelement.children
firstElementChildReturns the first child elementelement.firstElementChild
lastElementChildReturns the last child elementelement.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

September 25th, 2024

March 7th, 2026

Read time

7 min

Tags

javascriptcheatsheetprogrammingjs-cheatsheetweb-development
Follow us on GitHub
CoderrShyam logo

CoderrShyam

A professional web developer.

GithubTwitterBlue Sky

Resources

HomeAboutBlogContactTutorials

Socials

GitHubTwitterInstagramLinkedInFacebookThreadsBlue SkyStack OverflowReddit

Legal

Privacy PolicyTerms of Service

Authentication

ProfileLoginSignupForgot Password

© 2026CoderrShyamAll Rights Reserved.

CoderrShyam

Leave comment