Variables and Data Types
Store and manipulate data in your JavaScript applications.
The three declarations
var
var name = "John";- Function-scoped
- Can be redeclared
- Avoid in modern JS
let
let age = 30;- Block-scoped
- Can be reassigned
- Preferred for variables
const
const PI = 3.14;- Block-scoped
- Cannot be reassigned
- Default choice
Data Types
Primitive Types
- String
- Number
- Boolean
- Null
- Undefined
- Symbol
- BigInt
Structural Types
- Object
- Array
- Function
Use typeof operator to check types
Operators
Perform operations on variables and values.
Arithmetic
| Operator | Example | Meaning |
|---|---|---|
+ | 5 + 3 → 8 | Addition |
- | 10 - 2 → 8 | Subtraction |
* | 4 * 2 → 8 | Multiplication |
/ | 8 / 2 → 4 | Division |
% | 5 % 2 → 1 | Remainder |
** | 2 ** 3 → 8 | Exponentiation |
Comparison
| Operator | Example | Meaning |
|---|---|---|
== | '5' == 5 → true | Loose equality |
=== | '5' === 5 → false | Strict equality |
!= | '5' != 5 → false | Loose inequality |
!== | '5' !== 5 → true | Strict inequality |
> | 5 > 3 → true | Greater than |
< | 5 < 3 → false | Less than |
Logical
| Operator | Example | Meaning |
|---|---|---|
&& | true && false → false | Logical AND |
|| | true || false → true | Logical OR |
! | !true → false | Logical NOT |
Ternary Operator
const result = condition ? 'Yes' : 'No';Functions
Reusable blocks of code that perform specific tasks.
Function Types
Function Declaration
function greet(name) {
return `Hello, ${name}!`;
}- Hoisted (can be called before declaration)
- Has its own this context
Arrow Function (ES6+)
const greet = name => `Hello, ${name}!`;- Lexical this (inherits from parent scope)
- Concise syntax for simple functions
Advanced Features
Default Parameters
function greet(name = 'Guest') {
return `Hello, ${name}!`;
}Parameters can have default values when not provided
Rest Parameters
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}Collects all remaining arguments into an array
Closures
function outer() {
const message = 'Hello';
function inner() {
console.log(message);
}
return inner;
}Functions remember their lexical scope even when executed outside it
DOM Manipulation
Interact with and modify web page content.
Selecting Elements
Single Element
const el = document.querySelector('.class');Multiple Elements
const els = document.querySelectorAll('p');Traditional Methods
document.getElementById('id');
document.getElementsByClassName('class');
document.getElementsByTagName('div');Modifying Elements
Content
el.textContent = 'New text';
el.innerHTML = '<strong>Bold</strong> text';Attributes
el.setAttribute('id', 'newId');
el.className = 'active';Styles
el.style.color = 'blue';
el.style.fontSize = '20px';Event Handling
// Add event listener
button.addEventListener('click', function() {
console.log('Button clicked!');
});
// Common events
element.addEventListener('mouseover', handleHover);
input.addEventListener('focus', handleFocus);
form.addEventListener('submit', handleSubmit);Remember to remove event listeners with removeEventListener() when no longer needed to prevent memory leaks
Making Decisions in Code
Control what happens in your program based on conditions.
The Basic If Statement
Make simple yes/no decisions
// Check if user is old enough
const age = 18;
if (age >= 18) {
console.log("Access granted!");
}- JavaScript checks the condition in parentheses
- If true, runs the code inside the curly braces
- If false, skips the code block entirely
Real-world use: Validating inputs, checking permissions
If...Else Statement
Choose between two options
// Determine if a number is even or odd
const number = 7;
if (number % 2 === 0) {
console.log("Even number");
} else {
console.log("Odd number");
}- The
elseblock runs when the condition is false - Only one block will ever execute
- Great for binary (either/or) decisions
Try it: Change the number value and see what happens
Else If Ladder
Handle multiple possible conditions
// Grade calculator
const score = 85;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else if (score >= 70) {
console.log("Grade: C");
} else {
console.log("Grade: D or below");
}- Conditions are checked in order
- Only the first true condition runs
- The
elseat the end catches all remaining cases
Real-world use: Grading systems, tiered pricing
Switch Statement
Clean alternative to long else-if chains
// Handle different user roles
const role = 'editor';
switch (role) {
case 'admin':
console.log("Full access");
break;
case 'editor':
console.log("Can edit content");
break;
case 'viewer':
console.log("Can view only");
break;
default:
console.log("Unknown role");
}- Uses strict equality (
===) for comparisons breakprevents "falling through" to next casedefaultruns if no cases match
Tip: Use switch when comparing one variable against many exact values
Comparison Operators
Tools for creating conditions
| Operator | Meaning | Example |
|---|---|---|
=== | Strict equal (value and type) | 5 === 5 → true |
!== | Strict not equal | 5 !== "5" → true |
> | Greater than | 10 > 5 → true |
< | Less than | 10 < 5 → false |
>= | Greater than or equal | 10 >= 10 → true |
<= | Less than or equal | 10 <= 5 → false |
Using = (assignment) instead of === (comparison)
Loops — Repeating Actions
Learn how to repeat code blocks efficiently.
for Loop
Best when you know how many times to repeat
// Count from 0 to 4
for (let i = 0; i < 5; i++) {
console.log("Count:", i);
}- Start with
i = 0 - Check if
i < 5 - Run the code block
- Increase
iby 1 - Repeat until condition is false
Real-world use: Processing each item in a list
while Loop
Best when you're not sure how many times to repeat
// Keep asking until we get a valid age
let age;
while (!age || age < 0) {
age = prompt("Enter your age:");
}- Checks condition before running
- Might never run if condition is false initially
- Don't forget to update your condition!
Real-world use: Validating user input
do...while Loop
When you need to run at least once
// Show menu until user quits
let choice;
do {
choice = showMenu();
processChoice(choice);
} while (choice !== 'quit');- Runs code first, then checks condition
- Guaranteed to run at least once
- Useful for menus and user interactions
Real-world use: Game loops, menu systems
Working with Arrays
Modern ways to loop through arrays
1. forEach — Do something with each item
['dog', 'cat', 'bird'].forEach(pet => {
console.log('I have a', pet);
});Simple way to process each array element
2. map — Create a new array from an existing one
const lengths = ['dog', 'cat', 'bird']
.map(pet => pet.length);
// [3, 3, 4]Transform each element without changing the original
Tip: Start with forEach for simple loops, then learn map, filter, and reduce as you progress.
Arrays — Lists of Data
Store and manage collections of information.
Array Fundamentals
The building blocks of working with lists
// Create an array
let fruits = ['apple', 'banana', 'orange'];
// Access elements (starts at 0)
let first = fruits[0]; // 'apple'
let last = fruits[fruits.length - 1]; // 'orange'
// Update an element
fruits[1] = 'pear';- Arrays are zero-indexed (first item is 0)
- Use
lengthto get item count - Arrays can mix different data types
Create an array of your favorite colors and try accessing different positions.
Essential Array Methods
Most useful operations for beginners
Adding/Removing Items
fruits.push('grape'); // endfruits.pop(); // remove endFinding Items
fruits.includes('apple');fruits.indexOf('banana');Copying/Modifying
let some = fruits.slice(1,3);fruits.splice(1, 1);Remember: push/pop are for the end, slice makes copies, splice modifies the original.
Objects — Structured Data
Group related information together.
Object Basics
Key-value pairs for describing things
// Describe a person
let person = {
name: 'Alex',
age: 28,
hobbies: ['reading', 'hiking'],
address: {
city: 'Boston',
state: 'MA'
}
};Accessing Properties:
person.name // 'Alex'person['age'] // 28Think of objects like: A dictionary (word + definition) or a form (field name + value)
Modifying Objects
Changing and using your data
Adding/Updating Properties
// Add new property
person.job = 'Developer';
// Update existing
person.age = 29;
// Nested objects
person.address.zip = '02108';Adding Functions (Methods)
person.greet = function() {
console.log('Hello! My name is ' + this.name);
};
// Call the method
person.greet();Practice: Create an object for a book with title, author, and a method to display its info.
Helpful Object Utilities
Tools for working with objects
Object.keys()
const keys = Object.keys(person);
// ['name', 'age', 'hobbies', 'address']Get an array of all property names
Object.values()
const values = Object.values(person);
// ['Alex', 28, ['reading', 'hiking'], {...}]Get an array of all property values
Note: These methods return arrays, so you can use array methods like forEach on the results.
Hands-On Activities
Practice what you have learned with these interactive challenges.
Variable Challenge
Task:
Create three variables:
- A
constfor PI (3.14) - A
letfor a counter - A
varfor your name
// Your solution here
// Test your solution:
console.log(PI);
console.log(counter);
console.log(name);Function Challenge
Task:
Create a function that takes a name and returns a greeting message.
function greet(name) {
// Your code here
}
// Test your solution:
console.log(greet("Alice")); // Should output "Hello, Alice!"DOM Challenge
Task:
Select the button below and change its text when clicked.
const button = document.querySelector('#activity-btn');
button.addEventListener('click', () => {
// Your code here
});Array Challenge
Task:
Given this array, create a new array with only numbers greater than 5.
const numbers = [3, 8, 1, 5, 12, 4, 7];
// Your solution here
// Should output [8, 12, 7]Hint: Use the filter() method
