logo
eng-flag

JavaScript Cheatsheet

Table of Contents

  1. Variables and Data Types
  2. Operators
  3. Control Flow
  4. Functions
  5. Arrays
  6. Objects
  7. ES6+ Features
  8. DOM Manipulation
  9. Asynchronous JavaScript
  10. Error Handling

Variables and Data Types

Declaring Variables

// Using var (function-scoped)
var x = 5;

// Using let (block-scoped)
let y = 10;

// Using const (block-scoped, cannot be reassigned)
const PI = 3.14159;

Data Types

// Number
let num = 42;
let float = 3.14;

// String
let str = "Hello, World!";

// Boolean
let isTrue = true;
let isFalse = false;

// Undefined
let undefinedVar;

// Null
let nullVar = null;

// Symbol
let sym = Symbol("unique");

// BigInt
let bigInt = 1234567890123456789012345678901234567890n;

// Object
let obj = {name: "John", age: 30};

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

Type Checking

console.log(typeof 42);          // "number"
console.log(typeof "hello");     // "string"
console.log(typeof true);        // "boolean"
console.log(typeof undefined);   // "undefined"
console.log(typeof null);        // "object" (this is a known bug in JavaScript)
console.log(typeof Symbol());    // "symbol"
console.log(typeof {});          // "object"
console.log(typeof []);          // "object"
console.log(typeof function(){}); // "function"

Operators

Arithmetic Operators

let a = 10, b = 5;

console.log(a + b);  // Addition: 15
console.log(a - b);  // Subtraction: 5
console.log(a * b);  // Multiplication: 50
console.log(a / b);  // Division: 2
console.log(a % b);  // Modulus: 0
console.log(a ** b); // Exponentiation: 100000

// Increment and Decrement
let c = 5;
console.log(c++);    // 5 (post-increment)
console.log(++c);    // 7 (pre-increment)
console.log(c--);    // 7 (post-decrement)
console.log(--c);    // 5 (pre-decrement)

Comparison Operators

let x = 5, y = '5';

console.log(x == y);   // true (loose equality)
console.log(x === y);  // false (strict equality)
console.log(x != y);   // false (loose inequality)
console.log(x !== y);  // true (strict inequality)
console.log(x > 3);    // true
console.log(x < 3);    // false
console.log(x >= 5);   // true
console.log(x <= 5);   // true

Logical Operators

let a = true, b = false;

console.log(a && b);  // false (AND)
console.log(a || b);  // true (OR)
console.log(!a);      // false (NOT)

// Short-circuit evaluation
console.log(true && 'Hello');   // 'Hello'
console.log(false && 'Hello');  // false
console.log(true || 'Hello');   // true
console.log(false || 'Hello');  // 'Hello'

Assignment Operators

let x = 10;

x += 5;  // x = x + 5
console.log(x);  // 15

x -= 3;  // x = x - 3
console.log(x);  // 12

x *= 2;  // x = x * 2
console.log(x);  // 24

x /= 4;  // x = x / 4
console.log(x);  // 6

x %= 4;  // x = x % 4
console.log(x);  // 2

x **= 3; // x = x ** 3
console.log(x);  // 8

Control Flow

If-Else Statement

let age = 18;

if (age >= 18) {
    console.log("You are an adult");
} else if (age >= 13) {
    console.log("You are a teenager");
} else {
    console.log("You are a child");
}

Switch Statement

let day = "Monday";

switch (day) {
    case "Monday":
        console.log("Start of the work week");
        break;
    case "Friday":
        console.log("End of the work week");
        break;
    case "Saturday":
    case "Sunday":
        console.log("Weekend");
        break;
    default:
        console.log("Midweek");
}

For Loop

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

// Output: 0, 1, 2, 3, 4

While Loop

let i = 0;
while (i < 5) {
    console.log(i);
    i++;
}

// Output: 0, 1, 2, 3, 4

Do-While Loop

let i = 0;
do {
    console.log(i);
    i++;
} while (i < 5);

// Output: 0, 1, 2, 3, 4

For...of Loop (for iterables)

let arr = ['a', 'b', 'c'];
for (let item of arr) {
    console.log(item);
}

// Output: 'a', 'b', 'c'

For...in Loop (for object properties)

let obj = {a: 1, b: 2, c: 3};
for (let prop in obj) {
    console.log(prop + ': ' + obj[prop]);
}

// Output: 'a: 1', 'b: 2', 'c: 3'

Functions

Function Declaration

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

console.log(greet("John"));  // Output: "Hello, John!"

Function Expression

const greet = function(name) {
    return "Hello, " + name + "!";
};

console.log(greet("Jane"));  // Output: "Hello, Jane!"

Arrow Function

const greet = (name) => {
    return "Hello, " + name + "!";
};

// Shorter syntax for single expression
const greetShort = name => "Hello, " + name + "!";

console.log(greetShort("Alice"));  // Output: "Hello, Alice!"

Default Parameters

function greet(name = "Guest") {
    return "Hello, " + name + "!";
}

console.log(greet());  // Output: "Hello, Guest!"
console.log(greet("Bob"));  // Output: "Hello, Bob!"

Rest Parameters

function sum(...numbers) {
    return numbers.reduce((total, num) => total + num, 0);
}

console.log(sum(1, 2, 3, 4, 5));  // Output: 15

Arrays

Creating Arrays

let fruits = ['apple', 'banana', 'orange'];
let numbers = new Array(1, 2, 3, 4, 5);

Array Methods

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

// Adding elements
arr.push(6);  // Adds to the end
arr.unshift(0);  // Adds to the beginning

// Removing elements
arr.pop();  // Removes from the end
arr.shift();  // Removes from the beginning

// Finding elements
console.log(arr.indexOf(3));  // Returns 2
console.log(arr.includes(3));  // Returns true  

// Transforming arrays
let doubled = arr.map(num => num * 2);
let evenNumbers = arr.filter(num => num % 2 === 0);
let sum = arr.reduce((total, num) => total + num, 0);

// Iterating
arr.forEach(num => console.log(num));

// Sorting
arr.sort((a, b) => a - b);  // Ascending order

// Adding/Removing elements at specific positions
arr.splice(2, 0, 6, 7);  // Adds 6 and 7 at index 2: [1, 2, 6, 7, 3, 4, 5]
arr.splice(3, 2);        // Removes 2 elements starting from index 3: [1, 2, 6, 4, 5]

Objects

Creating Objects

let person = {
    name: "John",
    age: 30,
    greet: function() {
        console.log("Hello, my name is " + this.name);
    }
};

// Accessing properties
console.log(person.name);  // "John"
console.log(person['age']);  // 30

// Calling method
person.greet();  // "Hello, my name is John"

Object Methods

let keys = Object.keys(person);  // ['name', 'age', 'greet']
let values = Object.values(person);  // ['John', 30, [Function: greet]]
let entries = Object.entries(person);  // [['name', 'John'], ['age', 30], ['greet', [Function: greet]]]

// Merging objects
let obj1 = {a: 1, b: 2};
let obj2 = {c: 3, d: 4};
let merged = Object.assign({}, obj1, obj2);
// Or using spread operator
let mergedSpread = {...obj1, ...obj2};

ES6+ Features

Destructuring

// Array destructuring
let [a, b, c] = [1, 2, 3];
console.log(a, b, c);  // 1 2 3

// Object destructuring
let {name, age} = {name: "John", age: 30};
console.log(name, age);  // "John" 30

Spread Operator

let arr1 = [1, 2, 3];
let arr2 = [...arr1, 4, 5];  // [1, 2, 3, 4, 5]

let obj1 = {a: 1, b: 2};
let obj2 = {...obj1, c: 3};  // {a: 1, b: 2, c: 3}

Template Literals

let name = "John";
let greeting = `Hello, ${name}!`;
console.log(greeting);  // "Hello, John!"

Classes

class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    greet() {
        console.log(`Hello, my name is ${this.name}`);
    }
}

let john = new Person("John", 30);
john.greet();  // "Hello, my name is John"

DOM Manipulation

Selecting Elements

let element = document.getElementById('myId');
let elements = document.getElementsByClassName('myClass');
let elements = document.getElementsByTagName('div');
let element = document.querySelector('.myClass');
let elements = document.querySelectorAll('div');

Modifying Elements

element.innerHTML = 'New content';
element.setAttribute('class', 'newClass');
element.style.color = 'red';

Creating and Removing Elements

let newDiv = document.createElement('div');
newDiv.innerHTML = 'Hello, World!';
document.body.appendChild(newDiv);

element.parentNode.removeChild(element);
// Or
element.remove();

Event Handling

element.addEventListener('click', function(event) {
    console.log('Element clicked!');
});

Asynchronous JavaScript

Callbacks

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

fetchData(result => console.log(result));

Promises

function fetchData() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('Data fetched');
        }, 1000);
    });
}

fetchData()
    .then(result => console.log(result))
    .catch(error => console.error(error));

Async/Await

async function fetchData() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('Data fetched');
        }, 1000);
    });
}

async function getData() {
    try {
        const result = await fetchData();
        console.log(result);
    } catch (error) {
        console.error(error);
    }
}

getData();

Error Handling

Try-Catch

try {
    // Code that may throw an error
    throw new Error('Something went wrong');
} catch (error) {
    console.error(error.message);
} finally {
    console.log('This always runs');
}

Custom Errors

class CustomError extends Error {
    constructor(message) {
        super(message);
        this.name = 'CustomError';
    }
}

try {
    throw new CustomError('This is a custom error');
} catch (error) {
    console.error(error.name + ': ' + error.message);
}

2024 © All rights reserved - buraxta.com