JavaScript Cheat Sheet

Basic Syntax

JavaScript is a scripting language that enables dynamic interactivity on websites.

// Single-line comment
/* Multi-line
comment */

var x = 5;
let y = "Hello";
const z = true;

console.log(x + y);

Variables

Keyword Description Scope Reassignment Redeclaration
var Declares a variable. Function or global scope. Yes Yes (in the same scope)
let Declares a block-scoped, local variable. Block scope. Yes No
const Declares a block-scoped, read-only constant. Block scope. No No

Data Types

Type Description Example
String Represents textual data. "Hello", 'World', `Template literal`
Number Represents numeric data (integers and floating-point numbers). 10, 3.14, -5
Boolean Represents logical values (true or false). true, false
Null Represents the intentional absence of a value. null
Undefined Represents a variable that has not been assigned a value. undefined
Symbol A unique and immutable primitive value (introduced in ES6). Symbol('description')
BigInt Represents integers of arbitrary length (introduced in ES2020). 9007199254740991n
Object Represents a collection of key-value pairs. { name: 'John', age: 30 }, [1, 2, 3], function() {}

Operators

Operator Type Operators Description Example
Arithmetic +, -, *, /, %, ++, -- Perform arithmetic calculations. 5 + 2, x++
Assignment =, +=, -=, *=, /=, %= Assign values to variables. x = 10, y += 5
Comparison ==, ===, !=, !==, >, <, >=, <= Compare values. x == 5, y === "Hello"
Logical &&, ||, ! Perform logical operations. true && false, !true
Ternary condition ? exprIfTrue : exprIfFalse A shorthand for an if-else statement. age > 18 ? "Adult" : "Minor"
Type typeof, instanceof Determine the type of a variable or object. typeof x, arr instanceof Array

Control Flow

Statement Description Syntax
if Executes a block of code if a condition is true.
if (condition) {
  // code to be executed
}
else if Executes a block of code if the previous if condition is false and the current condition is true.
else if (condition) {
  // code to be executed
}
else Executes a block of code if all preceding if and else if conditions are false.
else {
  // code to be executed
}
switch Evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.
switch (expression) {
  case value1:
    // statements
    break;
  case value2:
    // statements
    break;
  default:
    // statements
}
for Loops through a block of code a number of times.
for (i = 0; i < 5; i++) {
  // code to be executed
}
while Loops through a block of code as long as a condition is true.
while (condition) {
  // code to be executed
}
do...while Loops through a block of code once, and then repeats as long as a condition is true.
do {
  // code to be executed
} while (condition);
break Exits a loop or a switch statement.
for (i = 0; i < 5; i++) {
  if (i === 3) break;
  // code
}
continue Skips the rest of the code in a loop for the current iteration.
for (i = 0; i < 5; i++) {
  if (i === 3) continue;
  // code
}

Functions

Type Description Syntax Example
Function Declaration Defines a named function.
function functionName(parameter1, parameter2) {
  // code to be executed
  return result;
}
function add(a, b) {
  return a + b;
}
let sum = add(5, 3);
Function Expression Defines a function as part of an expression.
const functionName = function(parameter1, parameter2) {
  // code to be executed
  return result;
};
const multiply = function(a, b) {
  return a * b;
};
let product = multiply(5, 3);
Arrow Function (ES6+) A concise way to write function expressions.
(parameter1, parameter2) => {
  // code to be executed
  return result;
};

// If only one parameter:
parameter => { // ... };

// If no parameters:
() => { // ... };

// Implicit return (for single expression):
(a, b) => a + b;
const divide = (a, b) => a / b;
let quotient = divide(15, 3);

Objects

Concept Description Example
Object Literal A way to define an object with properties and methods.
const person = {
  name: "John",
  age: 30,
  greet: function() {
    console.log(`Hello, my name is ${this.name}`);
  }
};
Accessing Properties Using dot notation or bracket notation.
person.name; // "John"
person["age"]; // 30
Accessing Methods Calling a function that is a property of an object.
person.greet(); // "Hello, my name is John"
this Keyword Refers to the object it belongs to. (See example above)

Arrays

Concept Description Example
Array Literal A way to define an array. const numbers = [1, 2, 3, 4, 5];
Accessing Elements Using index (starting from 0). numbers[0]; // 1
Common Methods Functions to manipulate arrays.
numbers.push(6); // Add to the end
numbers.pop(); // Remove from the end
numbers.shift(); // Remove from the beginning
numbers.unshift(0); // Add to the beginning
numbers.splice(2, 1, 10); // Add/remove elements
numbers.slice(1, 3); // Returns a new array
numbers.concat([7, 8]); // Joins arrays
numbers.join(", "); // Converts array to string
numbers.indexOf(3); // Returns first index of an element
numbers.lastIndexOf(3); // Returns last index
numbers.includes(4); // Checks if an array contains an element
numbers.forEach(num => console.log(num)); // Iterates over elements
numbers.map(num => num * 2); // Creates a new array with results
numbers.filter(num => num > 3); // Creates a new array with filtered elements
numbers.reduce((acc, curr) => acc + curr, 0); // Reduces array to a single value
numbers.sort(); // Sorts the array
numbers.reverse(); // Reverses the order

DOM Manipulation

Method Description Example
document.getElementById(id) Returns the element with the specified ID. const element = document.getElementById("myId");
document.getElementsByClassName(className) Returns a collection of elements with the specified class name. const elements = document.getElementsByClassName("myClass");
document.getElementsByTagName(tagName) Returns a collection of elements with the specified tag name. const elements = document.getElementsByTagName("p");
document.querySelector(selector) Returns the first element that matches a CSS selector. const element = document.querySelector("#myId .myClass");
document.querySelectorAll(selector) Returns a collection of all elements that match a CSS selector. const elements = document.querySelectorAll("div p");
element.innerHTML Gets or sets the HTML content of an element. element.innerHTML = "<strong>Hello</strong>";
element.textContent Gets or sets the text content of an element. element.textContent = "World";
element.getAttribute(attributeName) Gets the value of an attribute. const href = element.getAttribute("href");
element.setAttribute(attributeName, value) Sets the value of an attribute. element.setAttribute("href", "https://example.com");
element.style.propertyName Gets or sets inline CSS styles. element.style.color = "red";
document.createElement(tagName) Creates a new HTML element. const newElement = document.createElement("p");
parentElement.appendChild(childElement) Appends a child element to a parent element. parentElement.appendChild(newElement);
parentElement.insertBefore(newElement, referenceElement) Inserts a new element before a reference element. parentElement.insertBefore(newElement, referenceElement);
parentElement.removeChild(childElement) Removes a child element from a parent element. parentElement.removeChild(childElement);

Events

Concept Description Example
addEventListener(type, listener) Attaches an event listener to an element.
const button = document.getElementById("myButton");
button.addEventListener("click", function() {
  console.log("Button clicked!");
});
removeEventListener(type, listener) Removes an event listener from an element.
// Assuming 'myFunction' was the listener
button.removeEventListener("click", myFunction);
Common Events Examples include click, mouseover, mouseout, mousemove, keydown, keyup, submit, change. (See example above)
Event Object Provides information about the event.
element.addEventListener("click", function(event) {
  console.log(event.target); // The element that triggered the event
});

Asynchronous JavaScript

Concept Description Example
Callbacks A function passed as an argument to another function, to be executed later.
function getData(callback) {
  setTimeout(() => {
    const data = "Some data";
    callback(data);
  }, 1000);
}

getData(function(result) {
  console.log(result); // "Some data"
});
Promises (ES6+) An object representing the eventual completion (or failure) of an asynchronous operation.
const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Data received!");
    // reject("Error!");
  }, 1000);
});

promise
  .then(data => console.log(data))
  .catch(error => console.error(error))
  .finally(() => console.log("Promise finished"));
Async/Await (ES2017+) Syntactic sugar for working with promises, making asynchronous code look and behave a bit more like synchronous code.
async function fetchData() {
  try {
    const response = await fetch("https://api.example.com/data");
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error("Error fetching data:", error);
  }
}

fetchData();

Error Handling

Statement Description Syntax
try Defines a block of code to test for errors.
try {
  // Code that might throw an error
}
catch Defines a block of code to handle any errors that occur in the try block.
catch (error) {
  // Code to handle the error
  console.error("An error occurred:", error);
}
finally Defines a block of code to be executed regardless of the try-catch result.
finally {
  // Code to be executed after try or catch
}
throw Throws a custom error.
if (x < 0) {
  throw "x cannot be negative";
}

String Methods

Method Description Example
length Returns the length of a string. "Hello".length; // 5
charAt(index) Returns the character at a specified index. "Hello".charAt(0); // "H"
charCodeAt(index) Returns the Unicode value of the character at a specified index. "Hello".charCodeAt(0); // 72
concat(string) Joins two or more strings. "Hello".concat(" ", "World"); // "Hello World"
indexOf(searchValue, fromIndex) Returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex. Returns -1 if the value is not found. "Hello World".indexOf("o"); // 4
lastIndexOf(searchValue, fromIndex) Returns the index within the calling String object of the last occurrence of the specified value, searching backwards from fromIndex. Returns -1 if the value is not found. "Hello World".lastIndexOf("o"); // 7
slice(beginIndex, endIndex) Extracts a section of a string and returns it as a new string. "Hello World".slice(0, 5); // "Hello"
substring(indexStart, indexEnd) Returns the part of the string between the start and end indexes, or to the end of the string. "Hello World".substring(6); // "World"
substr(start, length) Returns a portion of the string, starting at the specified index and extending for a given number of characters. "Hello World".substr(6, 5); // "World"
replace(searchValue, newValue) Returns a new string with some or all matches of a pattern replaced by a replacement. "Hello World".replace("Hello", "Hi"); // "Hi World"
replaceAll(searchValue, newValue) Returns a new string with all matches of a pattern replaced by a replacement. "Hello Hello".replaceAll("Hello", "Hi"); // "Hi Hi"
toUpperCase() Returns the calling string value converted to uppercase. "hello".toUpperCase(); // "HELLO"
toLowerCase() Returns the calling string value converted to lowercase. "WORLD".toLowerCase(); // "world"
trim() Removes whitespace from both ends of a string. " Hello ".trim(); // "Hello"
split(separator) Splits a String object into an array of strings by separating the string into substrings. "Hello,World".split(","); // ["Hello", "World"]

Number Methods

Method Description Example
toFixed(digits) Formats a number using fixed-point notation. (3.14159).toFixed(2); // "3.14"
toPrecision(precision) Returns a string representing the Number object to the specified precision. (3.14159).toPrecision(3); // "3.14"
parseInt(string) Parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems). parseInt("10"); // 10, parseInt("10.5"); // 10
parseFloat(string) Parses a string argument and returns a floating point number. parseFloat("10.5"); // 10.5
isNaN(value) Determines whether a value is NaN (Not-a-Number). isNaN(NaN); // true, isNaN("Hello"); // true, isNaN(10); // false
isFinite(value) Determines whether a value is a finite number. isFinite(10); // true, isFinite(Infinity); // false

Math Object

Property/Method Description Example
Math.PI Returns the ratio of the circumference of a circle to its diameter, approximately 3.14159. Math.PI; // 3.141592653589793
Math.round(x) Returns the value of a number rounded to the nearest integer. Math.round(4.7); // 5, Math.round(4.4); // 4
Math.ceil(x) Returns the smallest integer greater than or equal to a given number. Math.ceil(4.4); // 5
Math.floor(x) Returns the largest integer less than or equal to a given number. Math.floor(4.7); // 4
Math.random() Returns a floating-point, pseudo-random number in the range 0 (inclusive) up to but not including 1 (exclusive). Math.random(); // e.g., 0.876...
Math.max(x, y, ...) Returns the largest of zero or more numbers. Math.max(10, 5, 20); // 20
Math.min(x, y, ...) Returns the smallest of zero or more numbers. Math.min(10, 5, 20); // 5
Math.pow(base, exponent) Returns base to the power of exponent. Math.pow(2, 3); // 8
Math.sqrt(x) Returns the square root of x. Math.sqrt(9); // 3

Date Object

Method Description Example
new Date() Creates a new Date object with the current date and time. const now = new Date();
new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds) Creates a new Date object with specified date and time. Note: monthIndex starts from 0 (January). const specificDate = new Date(2023, 10, 20, 10, 30, 0); // Nov 20, 2023 10:30:00
getFullYear() Returns the year of a date. now.getFullYear();
getMonth() Returns the month of a date (0-11). now.getMonth();
getDate() Returns the day of the month of a date (1-31). now.getDate();
getHours() Returns the hour of a date (0-23). now.getHours();
getMinutes() Returns the minutes of a date (0-59). now.getMinutes();
getSeconds() Returns the seconds of a date (0-59). now.getSeconds();
getMilliseconds() Returns the milliseconds of a date (0-999). now.getMilliseconds();
getTime() Returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. now.getTime();

JSON

Method Description Example
JSON.stringify(value) Converts a JavaScript value to a JSON string. const obj = { name: "John", age: 30 };
const jsonString = JSON.stringify(obj); // '{"name":"John","age":30}'
JSON.parse(text) Parses a JSON string, constructing the JavaScript value or object described by the string. const json = '{"name":"John","age":30}';
const parsedObj = JSON.parse(json); // { name: 'John', age: 30 }

Scope

Scope determines the accessibility (visibility) of variables.

Closures

A closure is a function that has access to the outer (enclosing) function's variables—scope chain—even after the outer function has returned.

function outerFunction(outerVar) {
  return function innerFunction(innerVar) {
    console.log(outerVar, innerVar);
  };
}

const myClosure = outerFunction("Hello");
myClosure("World"); // Output: Hello World

ES6+ Features (Brief Overview)

This cheat sheet provides a comprehensive overview of common JavaScript concepts and features. For more detailed information, refer to official JavaScript documentation and resources like MDN Web Docs.

```