Ultimate JavaScript & ES6+ Functions Cheat Sheet

A comprehensive guide to essential JavaScript functions and modern ES6+ features. Your one-stop reference for data manipulation, DOM interaction, asynchronous operations, and more.

Global & Core Functions

Fundamental functions for scripting, data type conversion, and URI handling.

  • console.log() - Outputs a message to the web console for debugging.
    console.log("Hello, Debugger!");
  • parseInt() - Parses a string argument and returns an integer of the specified radix.
    parseInt("42.5em", 10); // Returns 42
  • parseFloat() - Parses a string argument and returns a floating-point number.
    parseFloat("3.14 is pi"); // Returns 3.14
  • isNaN() - Determines whether a value is NaN (Not-A-Number).
    isNaN("Hello"); // true
  • isFinite() - Determines whether a value is a finite, legal number.
    isFinite(1/0); // false
  • encodeURI() / decodeURI() - Encodes/decodes a URI, ignoring characters needed for URI structure.
    const uri = "my test.asp?name=ståle";\nconst encoded = encodeURI(uri);
  • encodeURIComponent() / decodeURIComponent() - Encodes/decodes a URI component, including structural characters.
    const component = "https://example.com/?a=1&b=2";\nconst encodedComp = encodeURIComponent(component);

String Methods

Functions for manipulating and inspecting strings.

  • .length - Property that returns the length of a string.
    const str = "hello";\nconsole.log(str.length); // 5
  • .slice(start, end) - Extracts a section of a string and returns it as a new string.
    "JavaScript".slice(0, 4); // "Java"
  • .substring(start, end) - Similar to slice, but cannot accept negative indices.
    "JavaScript".substring(4, 10); // "Script"
  • .split(separator) - Splits a string into an array of substrings.
    "apple,banana,cherry".split(","); // ["apple", "banana", "cherry"]
  • .replace(pattern, replacement) - Returns a new string with some or all matches of a pattern replaced.
    "Hello World".replace("World", "JavaScript");
  • .toUpperCase() / .toLowerCase() - Converts the entire string to upper or lower case.
    "Hello".toUpperCase(); // "HELLO"
  • .trim() - Removes whitespace from both ends of a string.
    "   hello   ".trim(); // "hello"
  • .includes(searchString) - Determines whether one string may be found within another string.
    "Hello World".includes("World"); // true
  • .startsWith() / .endsWith() - Checks if a string begins or ends with the characters of a specified string.
    "filename.pdf".endsWith(".pdf"); // true
  • .padStart() / .padEnd() - Pads the current string with another string until it reaches a given length.
    "5".padStart(2, "0"); // "05"
  • .charAt(index) - Returns the character at the specified index.
    "hello".charAt(1); // "e"

Number & Math Methods

Functions for working with numbers and performing mathematical operations.

  • .toFixed(digits) - Formats a number using fixed-point notation (returns a string).
    const num = 123.456;\nnum.toFixed(2); // "123.46"
  • .toPrecision(precision) - Formats a number to a specified length (returns a string).
    const num = 123.456;\nnum.toPrecision(4); // "123.5"
  • Math.round() / .ceil() / .floor() - Rounds a number to the nearest integer, up, or down.
    Math.round(4.7); // 5\nMath.ceil(4.2);  // 5\nMath.floor(4.7); // 4
  • Math.random() - Returns a pseudo-random number between 0 (inclusive) and 1 (exclusive).
    Math.random(); // e.g., 0.123456789
  • Math.max() / .min() - Returns the largest/smallest of the given numbers.
    Math.max(10, 20, -5); // 20
  • Math.pow(base, exponent) - Returns the base to the exponent power.
    Math.pow(2, 3); // 8

Array Methods

A comprehensive list of methods for iterating over and transforming arrays.

  • .push() / .pop() - Adds elements to the end / Removes the last element from an array.
    const arr = [1, 2];\narr.push(3);   // arr is now [1, 2, 3]\narr.pop();      // returns 3, arr is [1, 2]
  • .shift() / .unshift() - Removes the first element / Adds new elements to the beginning of an array.
    const arr = [1, 2];\narr.shift();   // returns 1, arr is [2]\narr.unshift(0); // arr is now [0, 2]
  • .forEach(callback) - Executes a provided function once for each array element.
    ["a", "b"].forEach(item => console.log(item));
  • .map(callback) - Creates a new array with the results of calling a provided function on every element.
    const doubled = [1, 2, 3].map(num => num * 2); // [2, 4, 6]
  • .filter(callback) - Creates a new array with all elements that pass the test.
    const evens = [1, 2, 3, 4].filter(num => num % 2 === 0); // [2, 4]
  • .reduce(callback, initialValue) - Executes a reducer function, resulting in a single output value.
    const sum = [1, 2, 3].reduce((total, num) => total + num, 0); // 6
  • .find(callback) / .findIndex(callback) - Returns the first element/index that satisfies the test.
    const users = [{id:1, name:"John"}, {id:2, name:"Jane"}];\nusers.find(u => u.name === "Jane"); // {id:2, name:"Jane"}
  • .some(callback) / .every(callback) - Tests if at least one/all elements pass the test.
    [1, -5, 10].some(n => n < 0); // true\n[1, 5, 10].every(n => n > 0); // true
  • .slice(start, end) - Returns a shallow copy of a portion of an array into a new array object.
    const fruits = ["apple", "banana", "cherry", "date"];\nfruits.slice(1, 3); // ["banana", "cherry"]
  • .splice(start, deleteCount, ...items) - Changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
    const arr = [1, 2, 5];\narr.splice(2, 0, 3, 4); // arr is now [1, 2, 3, 4, 5]
  • .concat(...arrays) - Merges two or more arrays. Does not change the existing arrays.
    const arr1 = [1], arr2 = [2];\narr1.concat(arr2); // [1, 2]
  • .join(separator) - Joins all elements of an array into a string.
    ["Hello", "World"].join(" "); // "Hello World"
  • .flat(depth) / .flatMap(callback) - Creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
    const arr = [1, [2, 3]];\narr.flat(); // [1, 2, 3]\n\n[2, 3, 4].flatMap(x => [x, x*2]); // [2, 4, 3, 6, 4, 8]

Object Methods

Static methods for inspecting and manipulating objects.

  • Object.keys(obj) - Returns an array of a given object's own enumerable property names.
    Object.keys({a: 1, b: 2}); // ["a", "b"]
  • Object.values(obj) - Returns an array of a given object's own enumerable property values.
    Object.values({a: 1, b: 2}); // [1, 2]
  • Object.entries(obj) - Returns an array of a given object's own enumerable string-keyed property [key, value] pairs.
    Object.entries({a: 1, b: 2}); // [["a", 1], ["b", 2]]
  • Object.assign(target, ...sources) - Copies all enumerable own properties from one or more source objects to a target object.
    const target = {a: 1};\nconst source = {b: 2};\nObject.assign(target, source); // target is {a: 1, b: 2}
  • Object.freeze(obj) - Freezes an object, preventing new properties from being added and existing properties from being removed or modified.
    const obj = {prop: 42};\nObject.freeze(obj);\nobj.prop = 33; // Throws an error in strict mode
  • .hasOwnProperty(prop) - Returns a boolean indicating whether the object has the specified property as its own property.
    const person = {name: "John"};\nperson.hasOwnProperty("name"); // true

ES6+ Advanced Features

Modern JavaScript syntax for more readable, powerful, and asynchronous code.

  • Arrow Functions - A shorter syntax for writing function expressions.
    const add = (a, b) => a + b;
  • Destructuring - Unpacks values from arrays or properties from objects into distinct variables.
    const { name, age } = { name: "John", age: 30 };\nconst [first, second] = ["Apple", "Banana"];
  • Spread & Rest Operators (...) - Expands iterables into individual elements (spread) or collects multiple elements into an array (rest).
    const arr2 = [...arr1, 3, 4]; // Spread\nfunction sum(...numbers) { ... } // Rest
  • Promises - Represents the eventual completion (or failure) of an asynchronous operation.
    new Promise((resolve, reject) => { /* async code */ })
      .then(result => { /* handle success */ })
      .catch(error => { /* handle error */ })
      .finally(() => { /* cleanup */ });
  • Async/Await - Syntactic sugar for Promises, making async code look synchronous.
    async function fetchData() {\n  try {\n    const response = await fetch(url);\n    const data = await response.json();\n    console.log(data);\n  } catch (error) {\n    console.error(error);\n  }\n}
  • Optional Chaining (?.) - Permits reading the value of a property located deep within a chain of connected objects without having to validate each reference.
    const street = user?.address?.street; // Returns undefined if user or address is null/undefined
  • Nullish Coalescing (??) - A logical operator that returns its right-hand side operand when its left-hand side is null or undefined, and otherwise returns its left-hand side.
    const volume = null;\nconst safeVolume = volume ?? 50; // 50
  • Classes - A blueprint for creating objects with pre-defined properties and methods.
    class Car {\n  constructor(brand) { this.brand = brand; }\n  present() { return "I have a " + this.brand; }\n}\nconst myCar = new Car("Ford");
  • Modules (Import/Export) - Allows you to split your code into separate, reusable files.
    // In math.js
    export const add = (a, b) => a + b;
    
    // In main.js
    import { add } from './math.js';

DOM, Events & Browser APIs

Functions for interacting with the web page, handling user events, and using browser features.

  • document.querySelector() / .querySelectorAll() - Selects the first/all elements matching a CSS selector.
    const main = document.querySelector("#main");
  • element.addEventListener() / .removeEventListener() - Attaches/removes an event handler to an element.
    myButton.addEventListener("click", handleClick);
  • element.classList.add() / .remove() / .toggle() - Manages CSS classes on an element.
    element.classList.toggle("is-active");
  • element.getAttribute() / .setAttribute() - Gets or sets an attribute on an element.
    link.setAttribute("href", "https://example.com");
  • setTimeout() / clearTimeout() - Executes a function after a delay / Cancels it.
    const timerId = setTimeout(() => alert("Hi!"), 1000);
  • setInterval() / clearInterval() - Repeatedly executes a function with a fixed time delay / Cancels it.
    const intervalId = setInterval(() => console.log("tick"), 2000);
  • fetch(url, options) - The modern API for making network requests (replaces XMLHttpRequest).
    fetch("https://api.example.com/data")\n  .then(response => response.json())\n  .then(data => console.log(data));
  • localStorage.setItem() / .getItem() / .removeItem() - Provides a way to store key/value pairs in the browser persistently.
    localStorage.setItem("user", "John");\nconst user = localStorage.getItem("user");

JSON Methods

Functions for parsing and creating JSON (JavaScript Object Notation) strings.

  • JSON.stringify(object) - Converts a JavaScript object or value to a JSON string.
    const user = { name: "John", id: 5 };\nconst jsonString = JSON.stringify(user); // '{"name":"John","id":5}'
  • JSON.parse(string) - Parses a JSON string, constructing the JavaScript value or object described by the string.
    const jsonString = '{"name":"John","id":5}';\nconst userObject = JSON.parse(jsonString);