JavaScript

JavaScript Cheat Sheets

The most This cheat sheet covers the most common fundamentals of the JavaScript language. JavaScript reference card

Getting Started

// Hello World

console.log("Hello, World!");
Basic print statement

// Basic Commands

Single-line Comment
// This is a comment
Multi-line Comment
/* This is a multi-line comment */
Variable Declaration
let x = 5;
Output
console.log(x);
Input
let input = prompt("Enter something:");

Data Types

// Primitive Data Types

Number
Numeric data type
String
Sequence of characters
Boolean
true or false
Undefined
Variable not assigned a value
Null
Intentional absence of any value
Symbol
Unique and immutable data type
BigInt
Arbitrary-precision integers

// Type Conversion

let num = Number("123"); // 123
let str = String(123); // "123"
Casting between types

Operators

// Arithmetic Operators

+
Addition
-
Subtraction
*
Multiplication
/
Division
%
Modulus

// Comparison Operators

==
Equal to
!=
Not equal to
===
Strict equal to
!==
Strict not equal to
>
Greater than
<
Less than
>=
Greater than or equal to
<=
Less than or equal to

// Logical Operators

&&
Logical AND
||
Logical OR
!
Logical NOT

Control Flow

// if-else Statement

let x = 10;
if (x > 5) {
    console.log("Greater");
} else {
    console.log("Smaller or equal");
}
Conditional branching

// switch Statement

let day = 2;
switch (day) {
    case 1:
        console.log("Monday");
        break;
    case 2:
        console.log("Tuesday");
        break;
    default:
        console.log("Other");
}
Switch-case branching

// for Loop

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

// for...of Loop

let arr = [1,2,3];
for (let n of arr) {
    console.log(n);
}
For-of loop

// while Loop

let i = 0;
while (i < 3) {
    console.log(i);
    i++;
}
While loop

// do-while Loop

let i = 0;
do {
    console.log(i);
    i++;
} while (i < 3);
Do-while loop

// Loop Control Keywords

break
Exit the loop
continue
Skip to next iteration

Functions

// Function Declaration

function greet(name) {
    return "Hello, " + name;
}
Defining a function

// Arrow Function

const greet = (name) => "Hello, " + name;
ES6 arrow function

// Closure

function makeCounter() {
    let count = 0;
    return function() {
        return count++;
    };
}
Function with closure

Objects and Arrays

// Object Creation

let car = {
    brand: "Toyota",
    start: function() {
        console.log(this.brand + " is starting");
    }
};
Creating an object

// Array Methods

let arr = [1, 2, 3];
arr.push(4); // [1, 2, 3, 4]
arr.pop(); // [1, 2, 3]
Common array methods

// Prototype

function Person(name) {
    this.name = name;
}
Person.prototype.greet = function() {
    console.log("Hello, " + this.name);
};
Understanding prototypes

ES6 Features

// let and const

let x = 10;
const y = 20;
Block-scoped variables

// Template Literals

let name = "World";
console.log(`Hello, ${name}!`);
String interpolation

// Destructuring

let [a, b] = [1, 2];
let {name, age} = {name: "Alice", age: 25};
Extracting values from arrays or objects

Asynchronous JavaScript

// Callbacks

function fetchData(callback) {
    setTimeout(() => {
        callback("Data fetched");
    }, 1000);
}
Basic callback function

// Promises

let promise = new Promise((resolve, reject) => {
    resolve("Success");
});
promise.then(result => console.log(result));
Handling asynchronous operations

// Async/Await

async function fetchData() {
    let data = await fetch("/api/data");
    console.log(data);
}
Simplifying promise handling

DOM Manipulation

// Selecting Elements

let element = document.querySelector("#myElement");
DOM element selection

// Event Handling

element.addEventListener("click", function() {
    console.log("Element clicked");
});
Adding event listeners

Error Handling

// try-catch

try {
    let x = 1 / 0;
} catch (e) {
    console.log("Error: " + e.message);
}
Basic error handling

// Custom Error

class MyError extends Error {
    constructor(message) {
        super(message);
        this.name = "MyError";
    }
}
Creating custom error

Advanced Functions

// Higher-Order Functions

function map(arr, func) {
    let result = [];
    for (let i = 0; i < arr.length; i++) {
        result.push(func(arr[i]));
    }
    return result;
}
Functions that operate on other functions

// IIFE

(function() {
    console.log("IIFE");
})();
Immediately Invoked Function Expression

Modules

// ES6 Modules

export function greet() {
    console.log("Hello");
}
import { greet } from "./module.js";
Import and export syntax

Event Loop and Concurrency

// Event Loop

console.log("Start");
setTimeout(() => {
    console.log("Timeout");
}, 0);
console.log("End");
Understanding the event loop

Regular Expressions

// Regex Syntax

let regex = /\d+/;
console.log(regex.test("123"));
Basic regex patterns

Debugging

// Debugging Tools

console.log("Debugging");
debugger;
Using console and debugger

Security

// Common Security Concerns

XSS
Cross-Site Scripting
CSRF
Cross-Site Request Forgery

Performance Optimization

// Optimization Tips

Minimize DOM Access
Reduce the number of DOM manipulations
Use Efficient Selectors
Optimize CSS selectors

Web APIs

// Fetch API

fetch("/api/data")
    .then(response => response.json())
    .then(data => console.log(data));
Making network requests

// WebSockets

let socket = new WebSocket("ws://example.com/socket");
socket.onmessage = function(event) {
    console.log("Data received: " + event.data);
};
Real-time communication

TypeScript

// TypeScript Basics

let message: string = "Hello, TypeScript!";
Introduction to TypeScript

Testing

// Jest Testing

test("adds 1 + 2 to equal 3", () => {
    expect(1 + 2).toBe(3);
});
Unit testing with Jest

Best Practices

// JavaScript Best Practices

Code Organization
Use modules and namespaces
Error Handling
Use try-catch for error management

Tooling

// JavaScript Tools

Babel
JavaScript compiler
Webpack
Module bundler
ESLint
Linting utility

Case Studies

Land the career of your dreams!

Get inspired, learn, join competitions and grow in your job!

Sign up now