← Back to JavaScript Examples

Basic JavaScript

A quick-reference instruction sheet covering the fundamentals of JavaScript programming.

Contents

  1. What is JavaScript?
  2. Variables & Data Types
  3. Operators
  4. Strings
  5. Arrays
  6. Objects
  7. Control Structures
  8. Loops
  9. Functions
  10. DOM Manipulation
  11. Events
  12. Async JavaScript

1. What is JavaScript?

JavaScript is a lightweight, interpreted programming language that runs in the browser (and on servers via Node.js). It is the language of the web — used to make pages interactive.

// Inline in HTML
<script>
  console.log("Hello, World!");
</script>

// External file
<script src="app.js"></script>

2. Variables & Data Types

Use const by default, let when the value needs to change, and avoid var.

const name    = "Alice";      // String  — cannot be reassigned
let   age     = 30;           // Number  — can be reassigned
let   price   = 9.99;         // Number (JS has one number type)
const active  = true;         // Boolean
let   nothing = null;         // Null (intentional absence)
let   undef;                  // undefined (declared, not assigned)

console.log(typeof name);    // "string"
console.log(typeof age);     // "number"
console.log(typeof active);  // "boolean"
TypeExampleDescription
string"hello"Text
number42, 3.14All numbers (int and float)
booleantrue / falseBoolean values
nullnullIntentional empty value
undefinedundefinedVariable declared but not set
object{ key: val }Key-value pairs
array[1, 2, 3]Ordered list (technically an object)

3. Operators

Arithmetic

const a = 10, b = 3;
a + b;    // 13 — addition
a - b;    // 7  — subtraction
a * b;    // 30 — multiplication
a / b;    // 3.333… — division
a % b;    // 1  — modulus (remainder)
a ** b;   // 1000 — exponentiation

Comparison

x === y   // Strict equal (value AND type) ✓ always use this
x !== y   // Strict not equal
x ==  y   // Loose equal (type coercion — avoid)
x <   y   // Less than
x >   y   // Greater than
x <=  y   // Less than or equal
x >=  y   // Greater than or equal
Always use === instead of ==. Loose equality causes surprising results: "5" == 5 is true, but "5" === 5 is false.

Logical

a && b   // AND
a || b   // OR
!a        // NOT
a ?? b   // Nullish coalescing — use b if a is null/undefined

4. Strings

const first = "Alice";
const last  = "Smith";

// Concatenation
first + " " + last;            // "Alice Smith"

// Template literals (backticks) — preferred
`Hello, ${first}!`;              // "Hello, Alice!"
`${first} is ${2026 - 1996} years old.`;

// Common string methods
"hello".length;                 // 5
"hello".toUpperCase();          // "HELLO"
"hello".toLowerCase();          // "hello"
"  hello  ".trim();            // "hello"
"hello".includes("ell");        // true
"hello".startsWith("he");      // true
"hello".indexOf("l");          // 2
"hello".slice(1, 4);           // "ell"
"hello".replace("l", "r");     // "herlo"
"a,b,c".split(",");            // ["a","b","c"]
["a","b"].join("-");           // "a-b"

5. Arrays

const fruits = ["apple", "banana", "cherry"];
fruits[0];                      // "apple"
fruits.length;                  // 3
fruits.push("date");           // append — ["apple","banana","cherry","date"]
fruits.pop();                   // remove last — returns "date"
fruits.unshift("avocado");     // prepend
fruits.shift();                 // remove first
fruits.includes("banana");     // true
fruits.indexOf("cherry");      // 2
fruits.reverse();               // reverses in place
fruits.slice(1, 3);            // copy of elements [1] to [2]
fruits.join(" | ");            // "apple | banana | cherry"

Higher-Order Array Methods

const nums = [1, 2, 3, 4, 5];

// map — transform each element, returns new array
nums.map(n => n * 2);          // [2,4,6,8,10]

// filter — keep elements that pass a test
nums.filter(n => n > 2);        // [3,4,5]

// reduce — accumulate to a single value
nums.reduce((sum, n) => sum + n, 0); // 15

// find — first matching element
nums.find(n => n > 3);          // 4

// some / every
nums.some(n => n > 4);          // true (at least one)
nums.every(n => n > 0);         // true (all pass)

6. Objects

const person = {
    name: "Alice",
    age: 30,
    city: "NYC",
};

// Access
person.name;                    // "Alice" (dot notation)
person["age"];                 // 30     (bracket notation)

// Add / update / delete
person.email = "a@b.com";       // add
person.age   = 31;              // update
delete person.city;             // remove key

// Destructuring
const { name, age } = person;   // name = "Alice", age = 31

// Spread operator
const updated = { ...person, age: 32 }; // copy with override

// Keys and values
Object.keys(person);           // ["name","age","email"]
Object.values(person);         // ["Alice",31,"a@b.com"]
Object.entries(person);        // [["name","Alice"],["age",31],…]

7. Control Structures

if / else if / else

const score = 75;

if (score >= 90) {
    console.log("A");
} else if (score >= 75) {
    console.log("B");
} else if (score >= 60) {
    console.log("C");
} else {
    console.log("F");
}

switch

const day = "Mon";

switch (day) {
    case "Mon":
        console.log("Monday");
        break;
    case "Fri":
        console.log("Friday");
        break;
    default:
        console.log("Other day");
}

Ternary & Nullish Coalescing

// Ternary
const status = age >= 18 ? "adult" : "minor";

// Nullish coalescing — default if null or undefined
const username = inputName ?? "Guest";

// Optional chaining — safe property access
const city = user?.address?.city;   // undefined instead of error

8. Loops

for

for (let i = 0; i < 5; i++) {
    console.log(i);
}
// 0 1 2 3 4

for...of (arrays)

const fruits = ["apple", "banana", "cherry"];

for (const fruit of fruits) {
    console.log(fruit);
}

for...in (objects)

const person = { name: "Alice", age: 30 };

for (const key in person) {
    console.log(`${key}: ${person[key]}`);
}

while

let i = 0;
while (i < 5) {
    console.log(i);
    i++;
}
Use break to exit a loop early, and continue to skip to the next iteration.

9. Functions

Function Declaration

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

Arrow Functions

// Single expression — implicit return
const double = n => n * 2;
double(5);                    // 10

// Multiple params
const add = (a, b) => a + b;
add(3, 4);                    // 7

// Block body — explicit return needed
const greet = (name) => {
    const msg = `Hello, ${name}!`;
    return msg;
};

Default Parameters & Rest

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

// Rest parameter — collects remaining args into array
function sum(...nums) {
    return nums.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3, 4);             // 10

10. DOM Manipulation

The DOM (Document Object Model) is the browser's representation of the HTML page. JavaScript can read and modify it.

Selecting Elements

// Single element
document.getElementById("myId");
document.querySelector(".my-class");      // first match
document.querySelector("h1");

// Multiple elements (returns NodeList)
document.querySelectorAll(".card");       // all matches

Reading & Changing Content

const el = document.querySelector("#title");

el.textContent;                  // get text
el.textContent = "New Title";   // set text
el.innerHTML   = "<b>Bold</b>"; // set HTML (use carefully)

el.style.color = "red";         // inline style
el.classList.add("active");    // add class
el.classList.remove("active"); // remove class
el.classList.toggle("active"); // toggle class

el.getAttribute("href");        // read attribute
el.setAttribute("href", "/");  // set attribute

Creating & Removing Elements

const p = document.createElement("p");
p.textContent = "New paragraph";
document.body.appendChild(p);   // add to end of body

p.remove();                      // remove from DOM

11. Events

const btn = document.querySelector("#myBtn");

// Add event listener
btn.addEventListener("click", (event) => {
    console.log("Button clicked!");
    console.log(event.target);   // the element that was clicked
});

// Common event types
// "click"      — mouse click
// "dblclick"   — double click
// "mouseover"  — hover
// "keydown"    — key pressed
// "keyup"      — key released
// "submit"     — form submitted
// "input"      — input value changed
// "DOMContentLoaded" — page loaded

// Prevent default behaviour (e.g. form submission)
document.querySelector("form").addEventListener("submit", (e) => {
    e.preventDefault();
    console.log("Form intercepted");
});

12. Async JavaScript

JavaScript is single-threaded. Async patterns let you handle slow operations (network, timers) without blocking the page.

setTimeout & setInterval

// Run once after 2 seconds
setTimeout(() => {
    console.log("2 seconds later");
}, 2000);

// Run every second (returns an ID to cancel it)
const id = setInterval(() => {
    console.log("tick");
}, 1000);
clearInterval(id);              // stop it

Promises

const promise = new Promise((resolve, reject) => {
    const success = true;
    if (success) resolve("Done!");
    else         reject("Failed!");
});

promise
    .then(result => console.log(result))  // "Done!"
    .catch(err   => console.error(err));   // "Failed!"

async / await (preferred)

// fetch() returns a Promise — async/await makes it read like sync code
async function getUser() {
    try {
        const response = await fetch("https://api.example.com/user/1");
        const data     = await response.json();
        console.log(data.name);
    } catch (error) {
        console.error("Error:", error);
    }
}

getUser();
Always wrap await calls in a try/catch block to handle network errors gracefully.