cheetsheetz/javascript.md

4.5 KiB

JavaScript Cheat Sheet

Table of Contents

  1. Variables
  2. Data Types
  3. Operators
  4. Control Structures
  5. Functions
  6. Arrays
  7. Strings
  8. Objects
  9. DOM Manipulation
  10. Asynchronous JavaScript
  11. Error Handling

Variables

Declaration and Assignment

let variableName = value;

Variable Types

  • String: let stringVariable = "Hello";
  • Number: let numberVariable = 42;
  • Boolean: let boolVariable = true;
  • Undefined: let undefinedVariable;
  • Null: let nullVariable = null;

Data Types

Primitive Types

  • String
  • Number
  • Boolean
  • Undefined
  • Null

Reference Types

  • Object
  • Array
  • Function

Operators

Arithmetic Operators

+, -, *, /, %, ++, --

Comparison Operators

==, ===, !=, !==, <, >, <=, >=

Logical Operators

&& (and), || (or), ! (not)

Assignment Operators

=, +=, -=, *=, /=, %=

Control Structures

If Statement

if (condition) {
    // code to be executed if the condition is true
} else if (anotherCondition) {
    // code to be executed if the previous condition was false and this one is true
} else {
    // code to be executed if all conditions are false
}

Switch Statement

switch (variable) {
    case value1:
        // code to be executed if variable equals value1
        break;
    case value2:
        // code to be executed if variable equals value2
        break;
    default:
        // code to be executed if variable doesn't match any case
}

Loops

For Loop

for (let i = 0; i < 5; i++) {
    // code to be executed in each iteration
}

While Loop

while (condition) {
    // code to be executed as long as the condition is true
}

Do-While Loop

do {
    // code to be executed at least once, then repeated as long as the condition is true
} while (condition);

Functions

Function Declaration

function functionName(param1, param2) {
    // code to be executed
    return result; // optional
}

Arrow Functions

const add = (a, b) => a + b;

Function Call

let result = functionName(arg1, arg2);

Arrays

Array Declaration

let arrayName = [value1, value2, value3];

Array Methods

arrayName.push(newValue); // Add to the end
arrayName.pop(); // Remove from the end
arrayName.unshift(newValue); // Add to the beginning
arrayName.shift(); // Remove from the beginning

Strings

Template Literals

let name = "World";
let greeting = `Hello, ${name}!`;

String Methods

let str = "Hello, World!";
str.length; // Length of the string
str.indexOf("World"); // Index of the first occurrence of "World"
str.slice(start, end); // Extract a portion of the string

Objects

Object Declaration

let person = {
    name: "John",
    age: 30,
    isStudent: false
};

Object Methods

person.sayHello = function() {
    console.log(`Hello, my name is ${this.name}.`);
};

DOM Manipulation

Selecting Elements

let elementById = document.getElementById("elementId");
let elementByClass = document.getElementsByClassName("className");
let elementByTag = document.getElementsByTagName("tagName");

Modifying Elements

elementById.innerHTML = "New content";
elementById.style.color = "red";

Asynchronous JavaScript

Callbacks

function fetchData(callback) {
    // asynchronous operation
    setTimeout(() => {
        let data = "This is the data.";
        callback(data);
    }, 1000);
}

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

Promises

function fetchData() {
    return new Promise((resolve, reject) => {
        // asynchronous operation
        setTimeout(() => {
            let data = "This is the data.";
            resolve(data);
            // reject("Error occurred"); // Uncomment to simulate an error
        }, 1000);
    });
}

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

Error Handling

Try-Catch Block

try {
    // code that may throw an error
} catch (error) {
    // handle the error
    console.error("Error: " + error.message);
}