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";
Use for values that will change
const - Block Scoped
const PI = 3.14159;
Use for values that won't change
var - Function Scoped
var oldWay = "legacy";
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
x - y
m * n
p / q
n % m
x ** 2
Comparison
a == b
a === b
x != y
x !== y
a > b
a <= b
Logical
a && b
a || b
!a
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}!`;
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
function greet(name = "Guest") {
return `Hello, ${name}!`;
}
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];
const doubled = numbers.map(n => n * 2);
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
person["age"]
Destructuring
const { name, age } = person;
Spread Operator
const updated = {
...person,
age: 31
};
Object Methods
Object.keys(person)
Object.values(person)
Object.entries(person)
DOM Manipulation
The Document Object Model - interact with HTML elements using JavaScript.
Selecting Elements
const title = document.getElementById("myTitle");
const firstItem = document.querySelector(".item");
const allItems = document.querySelectorAll(".item");
Modifying Elements
element.textContent = "New text";
element.innerHTML = "<strong>Bold</strong>";
element.style.color = "red";
element.style.display = "none";
element.classList.add("active");
element.classList.remove("hidden");
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
button.addEventListener("click", handleClick);
function handleClick(event) {
console.log("Clicked!");
console.log(event.target);
}
<button onclick="myFunc()">Click</button>
ES6+ Modern JavaScript
Modern JavaScript features that make code cleaner.
Template Literals
const msg = "Hello " + name + "!";
const msg = `Hello ${name}!`;
Destructuring
const [a, b] = [1, 2];
const { x, y } = { x: 1, y: 2 };
Spread & Rest
const arr2 = [...arr1];
const sum = (...nums) => nums;
Optional Chaining
const city = user?.address?.city;
Nullish Coalescing
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