JavaScript Essentials

The Language of the Web

Variables Functions Objects DOM

Variables & Data Types

Variables store data. JavaScript has three ways to declare variables.

let - Block Scoped
let name = "John";
name = "Jane"; // Can be reassigned
Use for values that will change
const - Block Scoped
const PI = 3.14159;
// PI = 3; // Error!
Use for values that won't change
var - Function Scoped
var oldWay = "legacy";
// Avoid in modern JS
Legacy - avoid in new code
Data Types

Primitive Types:

  • String - Text: "Hello"
  • Number - Numbers: 42, 3.14
  • Boolean - true/false
  • Undefined - No value assigned
  • Null - Intentionally empty

Reference Types:

  • Object - Key-value pairs
  • Array - Ordered lists
  • Function - Reusable code

Operators

Operators perform operations on values.

Arithmetic
a + b // Addition
x - y // Subtraction
m * n // Multiplication
p / q // Division
n % m // Modulus (remainder)
x ** 2 // Exponentiation
Comparison
a == b // Loose equality
a === b // Strict equality
x != y // Not equal
x !== y // Strict not equal
a > b // Greater than
a <= b // Less or equal
Logical
a && b // AND - both true
a || b // OR - either true
!a // NOT - opposite

// Short-circuit evaluation
result = a && "yes";
Pro Tip: Use === Instead of ==

== performs type coercion (slow!). === compares both value AND type. Always use === for reliable comparisons!

Control Flow

Control the execution path of your code.

if / else if / else
const age = 18;

if (age >= 18) {
  console.log("Adult");
} else if (age >= 13) {
  console.log("Teenager");
} else {
  console.log("Child");
}
Switch Statement
const day = "Monday";

switch (day) {
  case "Monday":
    console.log("Start!");
    break;
  case "Friday":
    console.log("TGIF!");
    break;
  default:
    console.log("Regular day");
}
Loops
Loop Type Use Case Syntax
for Known iterations for(let i=0; i<5; i++)
while Unknown iterations while(condition)
for...of Iterate arrays for(let item of array)
for...in Iterate objects for(let key in object)

Functions

Functions are reusable blocks of code.

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

greet("World");
Function Expression
const greet = function(name) {
  return `Hello, ${name}!`;
};
Arrow Function
const greet = (name) => `Hello, ${name}!`;

// Single param, no parens
const double = x => x * 2;
Arrow Functions vs Regular Functions
  • Arrow functions are shorter and more concise
  • Arrow functions don't have their own this
  • Arrow functions can't be used as constructors
  • Use regular functions for methods, arrow for callbacks
Parameters & Arguments
// Default parameters
function greet(name = "Guest") {
  return `Hello, ${name}!`;
}

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

Arrays

Arrays store ordered collections of items.

const fruits = ["apple", "banana", "orange"];
Common Array Methods
Method Description Example
push() Add to end fruits.push("grape")
pop() Remove from end fruits.pop()
map() Transform each item fruits.map(f => f.toUpperCase())
filter() Filter items fruits.filter(f => f.length > 5)
reduce() Reduce to single value nums.reduce((a,b) => a+b)
find() Find first match fruits.find(f => f.startsWith("a"))
includes() Check if exists fruits.includes("banana")
Live Example
const numbers = [1, 2, 3, 4, 5];

// Double each number
const doubled = numbers.map(n => n * 2);
// Result: [2, 4, 6, 8, 10]

Objects

Objects store key-value pairs.

const person = {
  name: "John",
  age: 30,
  city: "NYC",
  greet: function() {
    return `Hi, I'm ${this.name}`;
  }
};
Access Properties
person.name // Dot notation
person["age"] // Bracket notation
Destructuring
const { name, age } = person;

// Creates: name = "John"
Spread Operator
const updated = {
  ...person,
  age: 31
};
Object Methods
Object.keys(person) // ["name", "age", "city", "greet"]
Object.values(person) // ["John", 30, "NYC", fn]
Object.entries(person) // [["name","John"], ...]

DOM Manipulation

The Document Object Model - interact with HTML elements using JavaScript.

Selecting Elements
// Single elements
const title = document.getElementById("myTitle");
const firstItem = document.querySelector(".item");

// Multiple elements
const allItems = document.querySelectorAll(".item");
Modifying Elements
// Change content
element.textContent = "New text";
element.innerHTML = "<strong>Bold</strong>";

// Change styles
element.style.color = "red";
element.style.display = "none";

// Add/remove classes
element.classList.add("active");
element.classList.remove("hidden");
Try It!
Output will appear here...

Event Handling

Respond to user interactions.

Common Events

Mouse:

  • click - Element clicked
  • mouseenter - Mouse enters
  • mouseleave - Mouse leaves
  • mousemove - Mouse moves

Keyboard:

  • keydown - Key pressed
  • keyup - Key released
  • input - Input changes
// Method 1: addEventListener
button.addEventListener("click", handleClick);

function handleClick(event) {
  console.log("Clicked!");
  console.log(event.target);
}

// Method 2: Inline (not recommended)
<button onclick="myFunc()">Click</button>

ES6+ Modern JavaScript

Modern JavaScript features that make code cleaner.

Template Literals
// Old
const msg = "Hello " + name + "!";

// New
const msg = `Hello ${name}!`;
Destructuring
// Arrays
const [a, b] = [1, 2];

// Objects
const { x, y } = { x: 1, y: 2 };
Spread & Rest
// Spread (expand)
const arr2 = [...arr1];

// Rest (collect)
const sum = (...nums) => nums;
Optional Chaining
// Safe property access
const city = user?.address?.city;
Nullish Coalescing
// Default for null/undefined
const name = value ?? "default";
Async/Await
const data = await fetch("/api");

Practical Exercise

Build an Interactive Todo List

Requirements:

  • Input field to add tasks
  • Add task on button click and Enter key
  • Display list of tasks
  • Delete button for each task
  • Mark tasks as complete
  • Use array methods (map, filter)
  • LocalStorage to persist data
  • Clean UI with CSS styling
Previous: CSS3 Back to Course