1. cheat-sheets
  2. /javascript

JavaScript Snippets for Quick Reference

Welcome to Web Reference's JavaScript snippets cheat sheet!

Whether you're a beginner or an experienced developer, this compilation provides a quick reference to essential JavaScript syntax and operations to help accelerate your workflow.

Core JavaScript Syntax

Basic syntax for variable declarations, function definitions, and control structures:

JS SnippetDescription
const variable = valueES6 syntax: Used to declare a constant variable with a value
let variable = valueES6 syntax: Used to declare a variable with a value
function foo()Used to define a function named foo
foo()Used to call the function foo
() => {}ES6 arrow function syntax
`template ${variable}`ES6 template literal syntax
{ property } = objectES6 destructuring syntax
if (condition)Executes code block if condition is true. E.g., if (condition) { /* code */ }
elseExecutes code block if preceding condition is false. E.g., if (condition) { /* code */ } else { /* code */ }
else if (condition)Checks another condition if preceding condition is false. E.g., if (condition) { /* code */ } else if (anotherCondition) { /* code */ }
switch (expression)Executes code blocks based on the value of expression. E.g., switch(expression) { case x: /* code block */ break; default: /* code block */ }
for (let i = 0; i < 10; i++)Creates a loop that iterates 10 times, incrementing the variable i by 1 each iteration.
while (condition)Used to create a loop that runs as long as the condition is true
do { ... } while (condition)Executes a block of code once, and then repeats it as long as the specified condition is true.
console.log(value)Prints the specified value to the console

DOM Manipulation

Snippets for interacting with the Document Object Model (DOM), and altering document structure, style, and content:

JS SnippetDescription
document.getElementById('id')Selects an element with the specified id
document.querySelector('selector')Selects the first element that matches the specified CSS selector
document.querySelectorAll('selector')Selects all elements that match the specified CSS selector
document.createElement('tagName')Creates a new HTML element with the specified tag name
element.addEventListener('event', handler)Attaches an event listener to the element
element.appendChild(childElement)Adds a child element to the element
element.removeChild(childElement)Removes a child element from the element
element.innerHTMLGets or sets the HTML content of the element
element.style.property = 'value'Sets a specific style property (e.g., color, font-size) of the element to the specified value. Ensure property is camelCased if it's a two-word property.
element.classList.add('class')Adds a class to the element's class list
element.classList.remove('class')Removes a class from the element's class list
element.classList.toggle('class')Toggles a class in the element's class list
element.setAttribute('attribute', 'value')Sets the value of an attribute on the element
element.removeAttribute('attribute')Removes an attribute from the element

Events

Event handling snippets for interactive user experiences:

JS SnippetDescription
element.onclick = functionSets the function to be called when the element is clicked
element.addEventListener('click', function)Adds a function to be called when the element is clicked
event.preventDefault()Prevents the default action of an event
event.stopPropagation()Stops the propagation of an event
new Event('event')Creates a new Event object. E.g., new Event('eventName')
element.dispatchEvent(event)Dispatches an event to the element

Browser Object Model (BOM)

Snippets for interacting with the browser, such as alerts, prompts, and timing events:

JS SnippetDescription
window.alert(message)Displays an alert dialog with a specified message
window.confirm(message)Displays a confirmation dialog with a specified message
window.prompt(message, default)Displays a dialog with a prompt, a specified message, and a default value
window.setTimeout(function, milliseconds)Sets a timer to execute a function after a specified number of milliseconds
window.setInterval(function, milliseconds)Sets a repeated timer to execute a function every specified number of milliseconds

Arrays

Array manipulation snippets for adding, removing, or modifying array elements:

JS SnippetDescription
array.push(element)Adds an element to the end of an array
array.pop()Removes the last element from an array
array.shift()Removes the first element from an array
array.unshift(element)Adds an element to the beginning of an array
array.slice(start, end)Creates a new array with elements from the specified range of an existing array
array.splice(start, deleteCount, ...items)Changes the contents of an array by removing, replacing, or adding elements. ...items is optional.
array.map(callback)Creates a new array by applying a function to every element of an array
array.filter(callback)Creates a new array with only the elements that pass a certain condition
array.reduce(callback)Reduces an array to a single value by applying a function to each element
array.forEach(callback)Executes a function on every element of an array
array.find(callback)Returns the first element that satisfies a specified condition
array.concat(array2)Merges two arrays

Objects

Snippets for working with object properties and methods:

JS SnippetDescription
object.propertyAccesses the value of a property on an object
object.property = valueSets the value of a property on an object
object.method()Calls a method on an object
Object.keys(object)Returns an array of a given object's own enumerable property names
Object.values(object)Returns an array of a given object's own enumerable property values
Object.entries(object)Returns an array of a given object's own enumerable property [key, value] pairs (string-keyed)

JSON Handling

Convert between JSON and JavaScript objects:

JS SnippetDescription
JSON.stringify(object)Converts an object to a JSON string
JSON.parse(string)Converts a JSON string to an object

Strings

String manipulation snippets for common operations like finding substrings or changing cases:

JS SnippetDescription
string.indexOf('substring')Finds the position of a substring in a string
string.substring(startIndex, endIndex)Extracts characters from a string between two specified indices
string.replace('old', 'new')Replaces a substring in a string with a new string
string.split('delimiter')Splits a string into an array based on a delimiter
string.trim()Removes whitespace from the beginning and end of a string
string.toLowerCase()Converts a string to lowercase
string.toUpperCase()Converts a string to uppercase
parseInt(string)Converts a string to an integer
parseFloat(string)Converts a string to a floating-point number
string.charAt(index)Returns the character at the specified index in a string
string.charCodeAt(index)Returns the Unicode of the character at the specified index in a string

Regular Expressions

Pattern matching and text manipulation with regular expressions:

JS SnippetDescription
/pattern/flagsCreates a regular expression object for matching text with a pattern
regexp.test(string)Tests for a match in a string
string.match(regexp)Finds all matches between a regular expression and a string
string.replace(regexp, newSubStr)Replaces matches between a regular expression and a string

Numbers and Math

Mathematical operations and number manipulation snippets:

JS SnippetDescription
Math.random()Generates a random floating-point number between 0 and 1
Math.floor(number)Rounds a number down to the nearest integer
Math.ceil(number)Rounds a number up to the nearest integer
Math.round(number)Rounds a number to the nearest integer
Math.min(n1, n2, ...)Finds the minimum value from a list of numbers (accepts multiple arguments)
Math.max(n1, n2, ...)Finds the maximum value from a list of numbers (accepts multiple arguments)
Math.abs(number)Gets the absolute value of a number
Math.pow(base, exponent)Calculates the power of a number
Math.sqrt(number)Calculates the square root of a number
Number.isInteger(value)Determines whether the passed value is an integer
Number.parseFloat(string)Parses a string argument and returns a floating point number
Number.parseInt(string, radix)Parses a string argument and returns an integer of the specified radix or base
Number.isNaN(value)Determines whether the passed value is NaN
Number.isFinite(value)Determines whether the passed value is a finite number

Date and Time

Snippets for working with Date objects and formatting dates and times:

JS SnippetDescription
new Date()Creates a new Date object representing the current date and time
date.getFullYear()Gets the year of a date, where date is an instance of the Date object
date.getMonth()Gets the month of a date (0-11, where 0 is January)
date.getDate()Gets the day of a month
date.getHours()Gets the hours of a date
date.getMinutes()Gets the minutes of a date
date.getSeconds()Gets the seconds of a date
date.setTime(milliseconds)Sets the date to the time equivalent to the given milliseconds since January 1, 1970, 00:00:00 UTC
date.toDateString()Returns the "date" portion of the Date as a human-readable string
date.toTimeString()Returns the "time" portion of the Date as a human-readable string

Error Handling

Error catching and custom error throwing snippets:

JS SnippetDescription
try { ... } catch(e) { ... }Catches and handles errors
throw new Error('message')Throws a custom error
console.error(e)Logs an error to the console, useful for debugging.

Promises and Async/Await

Handle asynchronous operations with promises and async/await syntax:

JS SnippetDescription
new Promise((resolve, reject) => { ... })Creates a new Promise
promise.then((value) => { ... })Handles a fulfilled promise
promise.catch((error) => { ... })Handles a rejected promise
async function functionName() { ... }Defines an asynchronous function
await expressionWaits for a Promise to resolve or reject
Promise.all(iterable)Returns a promise that resolves when all of the promises in the iterable argument have resolved, with an array of the results
Promise.race(iterable)Returns a promise that settles as soon as one of the promises in the iterable settles, with the value or reason from that promise

Web APIs

HTTP request snippets for fetching data from servers or external services:

JS SnippetDescription
fetch(url)Sends an HTTP request to the specified URL and returns a promise
fetch(url, options)Sends an HTTP request with options (method, headers, etc.) to the specified URL and returns a promise
Response.json()Reads the response to completion and parses it as JSON

Naturally, this isn't everything JavaScript entails. For more in-depth understanding feel free to check out our curated resources below.

Additional Resources

Introduction to JavaScript

Overview of ES6 JavaScript

A Brief History of ECMAScript Versions in JavaScript

Introduction to HTML Basics

Introduction to CSS

Guide to Graphics in Web Development

The 3rd Edition of Eloquent JavaScript (2018)