JavaScript Documentation

The programming language of the web - Make your websites interactive and dynamic

Introduction to JavaScript

JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled programming language with first-class functions. While it is most well-known as the scripting language for Web pages, many non-browser environments also use it, such as Node.js, Apache CouchDB and Adobe Acrobat.

ECMAScript 6 (ES6) and later versions brought significant improvements to JavaScript, including arrow functions, classes, modules, and more.

Basic Syntax

JavaScript statements are separated by semicolons. Whitespace is ignored.

Hello World

console.log("Hello, World!");

Comments

// Single line comment

/*
 * Multi-line
 * comment
 */

Variables

Variables are containers for storing data values. JavaScript has three ways to declare variables:

var, let, const

var x = 5;       // Function-scoped (avoid in modern JS)
let y = 10;      // Block-scoped, can be reassigned
const z = 15;    // Block-scoped, cannot be reassigned

Data Types

Type Example Description
String "Hello", 'World' Text data
Number 42, 3.14 Numeric data (integer or floating point)
Boolean true, false Logical values
Null null Intentional absence of any object value
Undefined undefined Variable has not been assigned a value
Object {}, [] Complex data structures
Symbol Symbol() Unique and immutable primitive value
BigInt 123456789012345678901234567890n Integer with arbitrary precision

Operators

Arithmetic Operators

Operator Name Example
+ Addition x + y
- Subtraction x - y
* Multiplication x * y
/ Division x / y
% Modulus (Remainder) x % y
** Exponentiation x ** y
++ Increment x++
-- Decrement x--

Comparison Operators

Operator Name Example
== Equal to x == y
=== Strict equal to x === y
!= Not equal x != y
!== Strict not equal x !== y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

Logical Operators

Operator Name Example
&& Logical AND (x < 10 && y > 5)
|| Logical OR (x < 10 || y > 5)
! Logical NOT !(x === y)

Functions

Functions are reusable blocks of code that perform a specific task.

Function Declaration

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

Function Expression

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

Arrow Function (ES6+)

const greet = (name) => `Hello, ${name!`;

Parameters and Arguments

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

add(5, 10); // Returns 15

Default Parameters

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

Rest Parameters

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

Objects

Objects are collections of key-value pairs. They are used to store various data and more complex entities.

Object Literal

const person = {
    name: "John",
    age: 30,
    isStudent: false,
    greet: function() {
        return `Hello, I'm ${this.name`;
    }
};

Accessing Properties

person.name;          // "John"
person["age"];       // 30
person.greet();      // "Hello, I'm John"

Object Methods

const keys = Object.keys(person);
const values = Object.values(person);
const entries = Object.entries(person);

Destructuring Objects

const { name, age } = person;
console.log(name); // "John"
console.log(age);  // 30

Arrays

Arrays are ordered collections of values. They are used to store multiple values in a single variable.

Creating Arrays

const fruits = ["Apple", "Banana", "Orange"];
const numbers = [1, 2, 3, 4, 5];
const mixed = [1, "two", true, {name: "John"}];

Array Methods

Method Description Example
push() Adds one or more elements to the end fruits.push("Mango")
pop() Removes the last element fruits.pop()
shift() Removes the first element fruits.shift()
unshift() Adds one or more elements to the beginning fruits.unshift("Kiwi")
slice() Returns a portion of the array fruits.slice(1, 3)
splice() Adds/removes elements at a specific index fruits.splice(1, 0, "Mango")
map() Creates a new array with the results of calling a function numbers.map(n => n * 2)
filter() Returns elements that pass a test numbers.filter(n => n > 2)
reduce() Reduces the array to a single value numbers.reduce((a, b) => a + b)
forEach() Executes a function for each element fruits.forEach(fruit => console.log(fruit))

Array Destructuring

const [first, second, ...rest] = fruits;
console.log(first);   // "Apple"
console.log(second);  // "Banana"
console.log(rest);    // ["Orange"]

DOM Manipulation

The Document Object Model (DOM) is a programming interface for HTML documents. It represents the page so that programs can change the document structure, style, and content.

Selecting Elements

const element = document.getElementById("myId");
const elements = document.getElementsByClassName("myClass");
const query = document.querySelector("#myId");
const queryAll = document.querySelectorAll(".myClass");

Modifying Elements

element.textContent = "New text";
element.innerHTML = "<strong>HTML content</strong>";
element.style.color = "red";
element.setAttribute("href", "https://example.com");

Event Listeners

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

// Common events: click, mouseover, mouseout, keydown, keyup, submit, change, etc.

Creating and Removing Elements

const newElement = document.createElement("div");
newElement.textContent = "New element";
parent.appendChild(newElement);

parent.removeChild(child);
element.remove(); // Modern way

Asynchronous JavaScript

JavaScript is single-threaded, but it can handle asynchronous operations using callbacks, promises, and async/await.

Callbacks

function fetchData(callback) {
    setTimeout(function() {
        callback("Data received");
    }, 1000);
}

fetchData(function(data) {
    console.log(data);
});

Promises

const promise = new Promise(function(resolve, reject) {
    if (success) {
        resolve("Success!");
    } else {
        reject("Error!");
    }
});

promise
    .then(function(result) {
        console.log(result);
    })
    .catch(function(error) {
        console.log(error);
    });

Async/Await (ES8+)

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);
    }
}

Fetch API

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

Practical Examples

Simple Calculator

function add(a, b) { return a + b; }
function subtract(a, b) { return a - b; }
function multiply(a, b) { return a * b; }
function divide(a, b) { return a / b; }

To-Do List

const todos = [];

function addTodo(text) {
    todos.push({ text: text, completed: false });
}

function completeTodo(index) {
    todos[index].completed = true;
}

function displayTodos() {
    todos.forEach((todo, index) => {
        console.log(${index + 1}. ${todo.text} - ${todo.completed ? 'Done' : 'Pending'});
    });
}

Image Slider

const images = ["image1.jpg", "image2.jpg", "image3.jpg"];
let currentIndex = 0;

function showNextImage() {
    currentIndex = (currentIndex + 1) % images.length;
    displayImage(images[currentIndex]);
}

function displayImage(src) {
    const img = document.getElementById("slider-image");
    img.src = src;
}

// Call showNextImage() every 3 seconds
setInterval(showNextImage, 3000);