JavaScript Reference

Variables and Data Types

Variables let you store values in your code. There are different kinds of values, we call them data types. Here are the most common ones:

// Variables
let name = "John";
const age = 25;
var oldWay = "don't use this";

// Data Types
let string = "Hello";
let number = 42;
let boolean = true;
let array = [1, 2, 3];
let object = { key: "value" };
let nullValue = null;
let undefinedValue = undefined;

Functions

Functions are blocks of code responsible for performing a specific task. They can be used to organize your code and make it more reusable.

// Function Declaration
function greet(name) {
    return `Hello, ${name}!`;
}

// Arrow Function
const greet = (name) => {
    return `Hello, ${name}!`;
};

// Function Expression
const greet = function(name) {
    return `Hello, ${name}!`;
};

Control Flow

Control flow is the order in which the code is executed. You can use if statements, switch statements, and loops to control the flow of your code.

// If Statement
if (age >= 18) {
    console.log("Adult");
} else if (age >= 13) {
    console.log("Teenager");
} else {
    console.log("Child");
}

// Switch Statement
switch (day) {
    case "Monday":
        console.log("Start of week");
        break;
    case "Friday":
        console.log("End of week");
        break;
    default:
        console.log("Middle of week");
}

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

while (condition) {
    // code
}

do {
    // code
} while (condition);

Arrays

Arrays are lists of values. You can use array methods to manipulate them.

// Array Methods
const numbers = [1, 2, 3, 4, 5];

// Map
const doubled = numbers.map(num => num * 2);

// Filter
const evenNumbers = numbers.filter(num => num % 2 === 0);

// Find
const firstEven = numbers.find(num => num % 2 === 0);

// Includes
const hasThree = numbers.includes(3);

Objects

Objects are collections of key-value pairs. You can use object methods to manipulate them.

// Object Creation
const person = {
    name: "John",
    age: 30,
    greet() {
        console.log(`Hello, I'm ${this.name}`);
    }
};

// Object Methods
Object.keys(person);     // Get all keys
Object.values(person);   // Get all values
Object.entries(person);  // Get key-value pairs

// Destructuring
const { name, age } = person;

DOM Manipulation

Javascript copies the HTML of your page and creates a a big object called the DOM tree. You can use DOM methods to manipulate the DOM.

// Selecting Elements
const element = document.getElementById('myId');
const elements = document.getElementsByClassName('myClass');
const tags = document.getElementsByTagName('div');
const query = document.querySelector('.myClass');
const queries = document.querySelectorAll('.myClass');

// Modifying Elements
element.innerHTML = 'New content';
element.style.color = 'red';
element.classList.add('newClass');
element.classList.remove('oldClass');
element.setAttribute('data-id', '123');

// Event Handling
element.addEventListener('click', (event) => {
    console.log('Clicked!');
});

Async JavaScript

Synchronous code is executed line by line. Asynchronous code is executed at the same time as the main thread. This is useful for handling events that take time to complete, such as fetching data from a server.

// Promises
const promise = new Promise((resolve, reject) => {
    // Async operation
    if (success) {
        resolve(result);
    } else {
        reject(error);
    }
});

// Async/Await
async function fetchData() {
    try {
        const response = await fetch('https://api.example.com/data');
        const data = await response.json();
        return data;
    } catch (error) {
        console.error('Error:', error);
    }
}