__ _______________________ _________._________________________ \_ _____/ \______ \ / _ \ / _____/ / _____/ | | \_ _____/ | __) | _/ / /_\ \ / \ ___ / \ ___ | | | __)_ | \ | | \ / | \ \ \_\ \ \ \_\ \ | |___ | \ \___ / |____|_ / \____|__ / \______ / \______ / |_______ \ /_______ / \/ \/ \/ \/ \/ \/ \/

JavaScript Quickstart Reference

← Back to quick reference

← Home


Quick reference guide for JavaScript. Essential syntax, control flow, data structures, and common patterns for web development and Node.js.


Hello World

console.log("Hello, World!");  // Basic output

Variables

let x = 42;            // Mutable variable
const name = "Alice";   // Immutable
let flag = true;        // Boolean
var old = "deprecated"; // Avoid var, use let/const

// Multiple declarations
let a = 1, b = 2, c = 3;

// Destructuring
let [x, y] = [1, 2];
let {name, age} = {name: "Alice", age: 30};

Control Flow

If/Else

if (x > 10) {
    console.log("x is big");
} else {
    console.log("x is small");
}

if (x > 10) {
    console.log("big");
} else if (x > 5) {
    console.log("medium");
} else {
    console.log("small");
}

// Ternary operator
let result = x > 10 ? "big" : "small";

// Switch
switch (x) {
    case 10:
        console.log("ten");
        break;
    case 20:
        console.log("twenty");
        break;
    default:
        console.log("other");
}

For Loops

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

// For...of (arrays, strings)
let nums = [1, 2, 3];
for (let n of nums) {
    console.log(n);
}

// For...in (object keys)
let person = {name: "Alice", age: 30};
for (let key in person) {
    console.log(key, person[key]);
}

// Array methods
nums.forEach(n => console.log(n));
nums.forEach((n, i) => console.log(i, n));

While Loops

while (x > 0) {
    x--;
    console.log(x);
}

// Do...while
do {
    x--;
} while (x > 0);

Functions

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

console.log(add(2, 3));

// Function expression
const subtract = function(a, b) {
    return a - b;
};

// Arrow functions
const multiply = (a, b) => {
    return a * b;
};

const divide = (a, b) => a / b;  // Implicit return

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

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

Arrays / Objects

Arrays

let nums = [1, 2, 3];
nums.forEach(n => console.log(n));

// Array methods
nums.push(4);           // Add to end
nums.pop();             // Remove from end
nums.unshift(0);        // Add to beginning
nums.shift();           // Remove from beginning
nums.length             // Length
nums[0]                 // Access by index
nums.slice(1, 3)         // Slice (non-mutating)
nums.splice(1, 1)        // Remove/insert (mutating)

// Array methods (functional)
nums.map(n => n * 2)    // Transform
nums.filter(n => n > 1) // Filter
nums.reduce((a, b) => a + b, 0)  // Reduce
nums.find(n => n > 1)    // Find first match
nums.some(n => n > 5)    // Any match
nums.every(n => n > 0)   // All match

Objects

let person = {name: "Alice", age: 30};
console.log(person.name);
console.log(person["name"]);

// Object methods
person.greet = function() {
    return `Hello, I'm ${this.name}`;
};

// Object literal with method shorthand
let person = {
    name: "Alice",
    age: 30,
    greet() {
        return `Hello, I'm ${this.name}`;
    }
};

// Object destructuring
let {name, age} = person;
let {name: n, age: a} = person;  // Rename

// Spread operator
let person2 = {...person, age: 31};

Maps and Sets

// Map
let map = new Map();
map.set("name", "Alice");
map.set("age", 30);
map.get("name");
map.has("name");
map.delete("name");

// Set
let set = new Set([1, 2, 3]);
set.add(4);
set.has(3);
set.delete(2);
set.size

Strings

let text = "Hello, World!";
let template = `Hello, ${name}!`;  // Template literal

// String methods
text.length
text.toUpperCase()
text.toLowerCase()
text.substring(0, 5)
text.slice(0, 5)
text.split(",")
text.replace("World", "JavaScript")
text.includes("Hello")
text.startsWith("Hello")
text.endsWith("!")

Classes

class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    
    greet() {
        return `Hello, I'm ${this.name}`;
    }
}

let person = new Person("Alice", 30);
console.log(person.greet());

// Inheritance
class Student extends Person {
    constructor(name, age, grade) {
        super(name, age);
        this.grade = grade;
    }
}

Promises & Async/Await

// Promises
let promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("Done!"), 1000);
});

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

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

// Promise.all
let promises = [promise1, promise2, promise3];
Promise.all(promises).then(results => {
    console.log(results);
});

Error Handling

try {
    let result = riskyOperation();
} catch (error) {
    console.error("Error:", error.message);
} finally {
    console.log("Always runs");
}

// Throwing errors
function divide(a, b) {
    if (b === 0) {
        throw new Error("Division by zero");
    }
    return a / b;
}

Modules (ES6)

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

export const PI = 3.14159;

export default class Calculator {
    // ...
}

// Import
import { add, PI } from "./math.js";
import Calculator from "./calculator.js";
import * as math from "./math.js";

Node.js Basics

// File system
const fs = require("fs");

// Reading
fs.readFile("file.txt", "utf8", (err, data) => {
    if (err) throw err;
    console.log(data);
});

// Writing
fs.writeFile("file.txt", "Hello, World!", (err) => {
    if (err) throw err;
});

// Promises (fs/promises)
const fs = require("fs/promises");
let data = await fs.readFile("file.txt", "utf8");

// Readline (user input)
const readline = require("readline");
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question("What's your name? ", (answer) => {
    console.log(`Hello, ${answer}!`);
    rl.close();
});

Tips

  • Variables: let mutable, const immutable. Avoid var.
  • prompt() (browser) or readline (Node.js) can handle user input.
  • JS is dynamically typed; type coercion can surprise you. Use === for strict equality.
  • Arrays are zero-indexed; objects are key-value maps.
  • Functions are first-class and can be anonymous or arrow-style.
  • Use const by default, let when reassignment is needed.
  • Template literals (backticks) allow string interpolation: `Hello, ${name}!`.
  • Arrow functions preserve this from enclosing scope; regular functions have their own this.
  • Use array methods (map, filter, reduce) for functional programming patterns.
  • Destructuring works with arrays and objects for cleaner code.
  • Use async/await for cleaner asynchronous code than promise chains.
  • null is intentional absence of value; undefined is uninitialized.
  • Use === and !== instead of == and != to avoid type coercion surprises.