javascript cheat sheet

JavaScript Cheat Sheet: A Basic Guide to JavaScript

March 30th, 2026
2507
20:00 Minutes

JavaScript is one of the most popular programming languages used for building interactive and dynamic websites. From simple form validation to advanced web applications, JavaScript plays a major role in modern web development. Whether you are a beginner learning the basics or an experienced developer looking for a quick reference, a JavaScript cheat sheet can help you save time and improve productivity.

This JavaScript cheat sheet covers essential concepts, syntax, operators, functions, loops, arrays, objects, DOM manipulation, ES6 features, and more in an easy-to-understand format. Instead of searching through lengthy documentation, you can quickly find commonly used JavaScript code snippets and examples in one place.

If you want to strengthen your front-end development skills, prepare for interviews, or speed up coding tasks, this guide will serve as a practical reference for everyday JavaScript programming. Keep this cheat sheet handy to quickly revise important concepts and write cleaner, more efficient code.

What is JavaScript?

JavaScript is the most widely used language for web development. It powers interactive websites, modern web apps, frontend frameworks, backend APIs, and even mobile applications. It runs primarily in web browsers and increasingly on servers using environments like Node.js.

It enables web pages to respond dynamically to user actions, manipulate HTML and CSS, communicate with servers, and handle complex logic. JavaScript supports multiple paradigms, including functional, object-oriented, and event-driven programming.

It is integral to the modern web ecosystem and works closely with HTML and CSS to build complete applications. Key Points you should know about it:

  • Runs in browsers and on servers (Node.js)
  • Used for interactivity, logic, and real-time updates
  • Single-threaded but supports asynchronous programming
  • Works with HTML and CSS to build full web experiences

Want to Learn Everything About JavaScript?

Boost your coding skills and gain hands-on knowledge in JavaScript.

Explore Now

JavaScript Basics and Syntax

JavaScript basics and syntax define the fundamental rules for writing valid code that the engine can interpret correctly. These include how statements are terminated, how whitespace is treated, how comments are written, and how names and identifiers are defined.

JavaScript is case sensitive and generally executes code from top to bottom, unless control structures like loops or conditionals change this order. Understanding basic syntax prevents runtime errors and forms the base for all future concepts.

Common Syntax Elements

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

console.log("Hello JavaScript"); // Output text
Concept Example Notes
Statement let x = 10; Usually ends with ;
Case-sensitive name vs Name Treated as different identifiers
Comments // or /* ... */ Ignored by the JavaScript engine
Whitespace let x = 5; Mostly ignored; use for readability

Related Article: JavaScript MCQs

Variables and Constants

Variables and constants are used to store values in memory so they can be reused and updated while the program runs. In JavaScript, you declare them using var, let, or const, each with different scoping and reassignment rules.

Choosing the right keyword improves code clarity and reduces bugs caused by accidental value changes. Modern JavaScript encourages using let for reassignable variables and const for values that should not be reassigned. Understanding these differences is essential for writing clean and maintainable code.

Declaration Keywords

var oldWay = 10;     // function scoped
let count = 5;       // block scoped
const PI = 3.1415;   // block scoped, cannot be reassigned

JavaScript Keywords

Category Keywords
Variables var, let, const
Conditions if, else, switch, case, default
Loops for, while, do, in, of
Functions/Classes function, class, extends, super, this, new
Modules import, export, default
Booleans/Null true, false, null, undefined
Operators typeof, instanceof, delete, await, async, yield
Reserved interface, private, enum, implements, protected

Data Types in JavaScript

Data types describe the kind of values that variables can store, which affects how they behave and what operations can be performed on them. JavaScript has primitive types such as number, string, boolean, null, undefined, symbol, and bigint, and non-primitive types such as objects, arrays, and functions.

Understanding the difference between primitive and reference types is important for predicting how values are copied and compared. Proper knowledge of data types helps avoid unexpected behavior, especially when dealing with equality, arithmetic operations, and JSON data.

Primitive Data Types

let age = 25;                // Number
let name = "JavaScript";     // String
let isActive = true;         // Boolean
let unknown;                 // Undefined
let empty = null;            // Null
let big = 900719925n;        // BigInt
let token = Symbol("id");    // Symbol

Non-Primitive Types

let user = { name: "Sam", age: 22 };  // Object
let list = [1, 2, 3];                 // Array
function greet() { return "Hi"; }     // Function

JavaScript Data Types

Category Data Type Description Example
Primitive Number Represents numeric values, integers & floats let x = 50;
Primitive String Text values written in quotes "Hello World"
Primitive Boolean Logical value is only true or false let isValid = true;
Primitive Null Represents an intentional empty value let value = null;
Primitive Undefined Declared but not assigned let a;
Primitive BigInt Very large integers beyond the Number limit 900719925n
Primitive Symbol Unique identifier value Symbol("id")
Non-Primitive Object Collection of key–value pairs {name: "Sam", age: 25}
Non-Primitive Array Ordered list of items, index-based [1, 2, 3]
Non-Primitive Function Executable reusable block function greet(){}

Operators

Operators are special symbols or keywords used to perform operations on values and variables, such as mathematical calculations, comparisons, logical decisions, and assignments. They help implement conditions, loops, and data transformations. JavaScript includes arithmetic, comparison, logical, assignment, bitwise, and ternary operators.

Understanding operator precedence and behavior, especially differences between == and ===, is crucial to avoiding subtle bugs. Operators are deeply integrated into expressions and control flow, making them fundamental to mastering JavaScript.

Common Operator Categories

let a = 10, b = 3;

a + b;       // Arithmetic
a > b;       // Comparison
a && b;      // Logical
a += 5;      // Assignment
let c = a > b ? a : b; // Ternary

Operators in JavaScript

Category Examples Purpose
Arithmetic + - * / % ** Math operations
Comparison == === != !== > < >= <= Compare values
Logical && || ! Combine or negate conditions
Assignment = += -= *= /= %= Update variables
Ternary condition ? value1 : value2 Short conditional expression

JavaScript Strings Cheat Sheet

Strings represent sequences of characters used for text-based data such as names, messages, and formatted content. JavaScript strings can be created using single quotes, double quotes, or backticks for template literals. They provide various built-in methods to search, modify, slice, and transform text.

Understanding string manipulation is important because user input, API responses, and UI content are often textual. Template literals make combining variables and strings more readable, especially when building dynamic messages or HTML fragments.

Basic String Usage

let text = "JavaScript Cheat Sheet";
text.length;                 // String length
text.toUpperCase();          // Uppercase
text.includes("Cheat");      // true

Useful String Methods

Method Description Example
toLowerCase() Converts to lowercase "HELLO".toLowerCase()
toUpperCase() Converts to uppercase "hello".toUpperCase()
slice(start, end) Extracts part of string "JavaScript".slice(0, 4) → Java
replace(a, b) Replaces first match "JS JS".replace("JS", "ES")
trim() Removes surrounding whitespace " hi ".trim()
split(separator) Splits into array "a,b,c".split(",")

Template Literals

let name = "Sanjay";
let msg = `Hello ${name}, welcome to JavaScript!`;

Arrays

Arrays are ordered collections of values used to store lists such as items, users, or results. They can contain any data type, including numbers, strings, objects, and even other arrays. Arrays provide powerful methods to add, remove, search, and transform elements, which are crucial for data processing and UI rendering.

Understanding core array operations and high-order functions like map, filter, and reduce makes JavaScript code more concise, expressive, and functional in style.

Basic Array Operations

let numbers = [1, 2, 3];
numbers.push(4);      // [1,2,3,4]
numbers.pop();        // [1,2,3]
numbers.shift();      // [2,3]
numbers.unshift(0);   // [0,2,3]

Important Array Methods

let arr = [1, 2, 3, 4, 5];

arr.map(x => x * 2);           // [2,4,6,8,10]
arr.filter(x => x > 2);        // [3,4,5]
arr.reduce((a, b) => a + b);   // 15
arr.find(x => x === 3);        // 3
arr.includes(4);               // true
Method Purpose
push() Add at end
pop() Remove from end
shift() Remove from start
unshift() Add at start
map() Transform each element
filter() Keep elements that match test
reduce() Combine into single value
find() Return first matching element

Objects

Objects are collections of key–value pairs that represent structured data such as users, products, or configurations. Each key, called a property, stores a value which can be any data type, including other objects and functions. Objects are central to JavaScript because many language features, including arrays and functions, are objects internally.

Understanding how to create, access, modify, and iterate over objects enables building complex data models and interacting effectively with APIs and frameworks.

Creating and Using Objects

let user = {
  name: "Sanjay",
  age: 25,
  isAdmin: false,
  greet: function () {
    return `Hello, ${this.name}`;
  }
};

user.name;          // "Sanjay"
user["age"];        // 25
user.email = "x@y.com";
delete user.isAdmin;
user.greet();       // "Hello, Sanjay"

Object Utility Methods

Object.keys(user);     // ["name","age","email","greet"]
Object.values(user);   // ["Sanjay",25,"x@y.com",function]
Object.entries(user);  // [["name","Sanjay"],...]
Method Description
Object.keys() Array of property names
Object.values() Array of property values
Object.entries() Array of [key, value] pairs
Spread {...} Shallow copy or merge objects

Functions

Functions are reusable blocks of code designed to perform specific tasks, improving structure, reusability, and readability. They can accept inputs called parameters and return outputs after processing. JavaScript supports function declarations, function expressions, arrow functions, and immediately invoked functions, making it highly flexible.

Functions are essential for modularizing logic, handling events, processing data, and working with asynchronous operations. Understanding scope and this binding in functions is critical for building reliable applications.

Function Forms

// Function declaration
function add(a, b) {
  return a + b;
}

// Function expression
const multiply = function (a, b) {
  return a * b;
};

// Arrow function
const divide = (a, b) => a / b;

Default and Rest Parameters

function greet(name = "Guest") {
  return `Hello, ${name}`;
}

function sum(...nums) {
  return nums.reduce((a, b) => a + b, 0);
}
Type Example
Declaration function fn(){}
Expression const fn = function(){}
Arrow Function const fn = () => {}
IIFE (function(){})();

Control Flow and Conditionals

Control flow structures determine how and when different parts of your code execute. In JavaScript, conditionals like if, else if, else, and switch help you make decisions based on dynamic values and user input. Proper use of conditionals ensures that your programs behave correctly under various scenarios.

They are especially important when validating forms, handling API responses, and implementing business rules. Understanding control flow makes debugging easier and logic more predictable.

If–Else and Switch

let score = 85;

if (score >= 90) {
  console.log("A");
} else if (score >= 75) {
  console.log("B");
} else {
  console.log("C");
}

let role = "admin";
switch (role) {
  case "admin":
    console.log("Full access");
    break;
  case "user":
    console.log("Limited access");
    break;
  default:
    console.log("Guest access");
}

Loops and Iteration

Loops allow your program to repeat actions without duplicating code manually, making it easier to process collections, perform repeated checks, and automate tasks. JavaScript provides traditional loops like for, while, and do...while, along with more modern constructs like for...of and for...in.

Choosing the right loop depends on whether you are iterating arrays, objects, or custom iterables. Efficient use of loops improves performance and readability, especially when handling lists from APIs or dynamically generating UI elements.

Common Loop Types

// Classic for loop
for (let i = 0; i < 5; i++) {
  console.log(i);
}

// While loop
let n = 3;
while (n > 0) {
  console.log(n);
  n--;
}

// For...of for arrays
for (let value of [10, 20, 30]) {
  console.log(value);
}

// For...in for objects
let user = { name: "Sam", age: 20 };
for (let key in user) {
  console.log(key, user[key]);
}

Scope, Hoisting, and Closures

Scope defines where variables and functions are accessible within your code, affecting how data is shared and protected. Hoisting is JavaScript’s behavior of moving declarations to the top of their scope during compilation, which can cause surprising results if misunderstood.

Closures occur when an inner function retains access to variables from its outer function even after the outer function has finished execution. These concepts together influence variable lifetime, memory usage, and encapsulation, making them crucial for advanced JavaScript development and interview questions.

Closure Example

function counter() {
  let count = 0;
  return function () {
    count++;
    return count;
  };
}

const increment = counter();
increment(); // 1
increment(); // 2
Concept Description
Scope Visibility of variables and functions
Hoisting Declarations appear as if moved up
Closure Function with preserved outer scope

DOM Manipulation

The Document Object Model (DOM) represents an HTML page as a tree of nodes that JavaScript can access and modify. DOM manipulation allows you to change text, structure, styles, attributes, and even create or remove elements dynamically.

This capability is essential for building interactive interfaces, handling user input, and updating content without reloading the page. Mastering DOM APIs forms the core of client-side JavaScript and is heavily used even within frameworks that abstract some of these details.

Selecting and Modifying Elements

const title = document.getElementById("title");
const items = document.querySelectorAll(".item");

title.innerText = "Updated Title";
title.style.color = "blue";

Creating and Appending Elements

const newItem = document.createElement("li");
newItem.innerText = "New List Item";
document.querySelector("ul").appendChild(newItem);
Task Method
Select by ID getElementById("id")
Select by class getElementsByClassName()
CSS selector querySelector()
Multiple nodes querySelectorAll()
Create element createElement("tag")
Insert appendChild(node)

Events and Event Handling

Events are notifications that something has happened in the browser, such as a click, key press, mouse movement, or form submission. Event handling in JavaScript means listening for these events and executing functions in response.

This mechanism is central to interactive web applications, enabling buttons to perform actions, forms to validate input, and elements to react to user behavior. Understanding event propagation, default actions, and event listeners ensures smooth and predictable user experiences.

Adding Event Listeners

const btn = document.getElementById("submitBtn");

btn.addEventListener("click", function (event) {
  event.preventDefault();
  console.log("Button clicked!");
});
Common Event Description
click Mouse click
submit Form submission
input Input value change
keyup Key released
load Page loaded

ES6+ Core Features

ES6 and later versions introduced powerful features that modernized JavaScript, making code more concise, readable, and modular. Important additions include let and const for safer variable declarations, arrow functions for shorter syntax, template literals for easier string interpolation, destructuring for concise assignment, and the spread and rest operators for flexible handling of arrays and objects.

These features are widely used in modern codebases, libraries, and frameworks, so understanding them is essential for contemporary JavaScript development.

Examples of Key ES6 Features

// Template literal
const name = "Sam";
const message = `Hello, ${name}!`;

// Destructuring
const user = { name: "Sam", age: 25 };
const { age } = user;

// Spread
const arr1 = [1, 2];
const arr2 = [3, 4];
const merged = [...arr1, ...arr2];
Feature Example Benefit
let / const let x = 1; const y = 2; Better scoping
Arrow functions x => x * 2 Shorter, lexical this
Template literals `Hello ${name}` Easy interpolation
Destructuring const {a} = obj; Cleaner assignments
Spread / Rest [...arr] / (...args) Flexible parameter and merging

Asynchronous JavaScript (Callbacks, Promises, async/await)

Asynchronous JavaScript allows non-blocking operations, enabling the program to continue running while waiting for tasks such as network requests, timers, or file reads. Initially, callbacks were used, but they often led to nested and hard-to-read code. Promises improved this by representing future values with clearer chaining, and async/await made asynchronous code look synchronous while still remaining non-blocking.

Understanding this model is critical for calling APIs, handling user actions smoothly, and building responsive applications.

Callback Example

setTimeout(() => {
  console.log("Executed later");
}, 1000);

Promise and async/await

function fetchData(url) {
  return fetch(url).then(response => response.json());
}

async function loadUser() {
  const user = await fetchData("/api/user");
  console.log(user);
}

Error Handling

Error handling is the process of gracefully detecting and managing issues that occur while your code runs, such as invalid inputs, failed network requests, or unexpected values. JavaScript provides try...catch blocks to intercept thrown errors and prevent the entire application from crashing. You can also create and throw custom errors to signal specific problems in business logic.

Proper error handling improves reliability, user experience, and debuggability, especially in production applications that interact with external systems.

Try–Catch–Finally

try {
  riskyOperation();
} catch (error) {
  console.error("Something went wrong:", error.message);
} finally {
  console.log("Cleanup logic here");
}

Throwing Custom Errors

function divide(a, b) {
  if (b === 0) {
    throw new Error("Cannot divide by zero");
  }
  return a / b;
}

JSON and Data Exchange

JSON (JavaScript Object Notation) is a lightweight data format used to exchange information between clients and servers. It represents data as nested objects and arrays with key–value pairs, making it easy for JavaScript to parse and generate. JSON is the standard format for REST APIs and configuration files.

JavaScript provides built-in methods JSON.stringify to convert objects to JSON strings, and JSON.parse to convert JSON strings back into objects. Mastering JSON is essential for working with APIs and external services.

JSON Usage

const user = { name: "Sam", age: 25 };

const json = JSON.stringify(user);   // Object → JSON string
const obj = JSON.parse(json);        // JSON string → Object
Method Description
JSON.stringify Object to JSON string
JSON.parse JSON string to object

Browser Storage (localStorage, sessionStorage)

Browser storage mechanisms allow web applications to store data on the client side, preserving state or user preferences between page reloads. localStorage stores data with no expiration date, while sessionStorage keeps data only for the current tab session. Both store key–value pairs as strings.

These tools are useful for caching, remembering themes, or saving form data. Understanding client-side storage is important for enhancing performance and improving the user experience without always hitting the server.

localStorage Example

localStorage.setItem("theme", "dark");
const theme = localStorage.getItem("theme");
localStorage.removeItem("theme");

sessionStorage Example

sessionStorage.setItem("token", "abc123");
const token = sessionStorage.getItem("token");
sessionStorage.clear();
Storage Type Lifetime Common Use Cases
localStorage Until cleared Preferences, simple cache
sessionStorage Until tab is closed Session data, temp state

Fetch API and HTTP Requests

The Fetch API is a modern interface for making HTTP requests from the browser, replacing older mechanisms like XMLHttpRequest. It returns promises, making it easy to chain actions or use with async/await. Fetch is commonly used to call REST APIs, submit data, and retrieve resources such as JSON, text, or files.

Understanding how to send GET, POST, and other HTTP methods with Fetch is crucial for building interactive, data-driven applications that communicate with backends.

Basic Fetch Example

fetch("https://api.example.com/users")
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error("Error:", error));

Using async/await with Fetch

async function loadUsers() {
  try {
    const response = await fetch("https://api.example.com/users");
    const users = await response.json();
    console.log(users);
  } catch (error) {
    console.error("Error:", error);
  }
}

Modules and Import/Export

Modules allow you to split JavaScript code into separate files, improving organization, reusability, and maintainability in larger projects. Using export, you can expose variables, functions, or classes from one file, and import them into another. ES modules support both named and default exports.

Modules help create clear boundaries between components and avoid polluting the global namespace. They are widely used in modern bundlers and frameworks such as React, Vue, and Angular.

Export and Import Examples

// math.js
export function add(a, b) {
  return a + b;
}

export const PI = 3.14;

// main.js
import { add, PI } from "./math.js";
console.log(add(2, 3), PI);

Default Export

// logger.js
export default function log(message) {
  console.log(message);
}

// main.js
import log from "./logger.js";
log("Hello");

Classes and Object-Oriented Patterns

Classes provide a cleaner syntax for creating objects and managing inheritance, built on top of JavaScript’s prototype-based system. They encapsulate data and behavior into reusable blueprints, making it easier to model real-world entities like users, products, and orders. Classes support constructors, methods, getters, setters, and inheritance using the extends keyword.

Understanding classes is important for working with frameworks, libraries, and more structured codebases that follow object-oriented patterns.

Class Example

class User {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  
  greet() {
    return `Hello, ${this.name}`;
  }
}

class Admin extends User {
  constructor(name, age, role) {
    super(name, age);
    this.role = role;
  }
}

const admin = new Admin("Sanjay", 25, "superadmin");
admin.greet();

Useful Built-in Objects (Math, Date)

JavaScript provides several built-in objects that simplify common tasks, such as math operations and date–time handling. The Math object offers utilities for rounding, random numbers, and trigonometry, while the Date object represents moments in time and provides methods to get and set components like year and month.

Leveraging these objects saves time and avoids reinventing standard functionality, making your code more concise and reliable.

Math Examples

Math.round(4.6);    // 5
Math.floor(4.9);    // 4
Math.ceil(4.1);     // 5
Math.random();      // 0 to <1
Math.max(1, 5, 2);  // 5

Date Example

const now = new Date();
now.getFullYear();
now.getMonth();    // 0-based
now.getDate();

Want to Master Web Development?

Boost your coding skills and gain hands-on knowledge in Web Development.

Explore Now

Conclusion

This JavaScript cheat sheet is designed to help you in learning, revising, or writing code confidently. From variables and operators to arrays, functions, objects, DOM, asynchronous programming, and ES6 features, this reference guide helps beginners and developers quickly recall essential concepts without searching repeatedly.

Keep this cheat sheet bookmarked, practice frequently, and build small projects. The more you code, the faster these concepts become second nature. JavaScript continues to evolve, and understanding fundamentals is the key to mastering frameworks like React, Node.js, and Vue in the future.

Frequently Asked Questions

1. Who is this JavaScript cheat sheet for?

This cheat sheet is perfect for beginners, students, and working developers who want a quick reference for JavaScript syntax, data types, functions, ES6, DOM, and more. It eliminates repeated searching and provides everything essential in one place.

2. Can I use this JavaScript cheat sheet for interviews?

Yes. Many interview questions are based on core JavaScript concepts, like variables, closures, arrays, objects, scope, promises, async/await, and DOM manipulation. This cheat sheet helps you revise fast and confidently before interviews or coding tests.

3. Is JavaScript difficult to learn?

Not if you practice consistently. It is beginner-friendly and widely supported, making it great for new developers. With this cheat sheet plus regular coding, projects, and debugging, you can learn JavaScript faster and more efficiently.

Articles You Can Also Read:

About the Author
Sanjay Prajapat
About the Author

Sanjay Prajapat is a Data Engineer and technology writer with expertise in Python, SQL, data visualization, and machine learning. He simplifies complex concepts into engaging content, helping beginners and professionals learn effectively while exploring emerging fields like AI, ML, and cybersecurity in today’s evolving tech landscape.

Drop Us a Query
Fields marked * are mandatory
Recent Post
×

Your Shopping Cart


Your shopping cart is empty.