1. Introduction to JavaScript
JavaScript is a versatile programming language used to make web pages interactive. It can update content, validate forms, handle events, and communicate with servers. JavaScript runs in the browser and is an essential part of modern web development alongside HTML and CSS.
2. Including JavaScript
You can include JavaScript in three ways:
- Inline JS: Directly in HTML tags using attributes like
onclick. - Internal JS: Inside a
<script>tag within HTML. - External JS: Using a separate
.jsfile linked via<script src="file.js"></script>.
3. Variables & Data Types
Variables store data. Use let or const (avoid var).
Common data types: String, Number, Boolean,
null, undefined.
4. Operators
Operators perform operations on values. JavaScript has several types of operators:
1. Arithmetic Operators
+: Addition →5 + 3 = 8-: Subtraction →5 - 3 = 2*: Multiplication →5 * 3 = 15/: Division →15 / 3 = 5%: Modulus (Remainder) →10 % 3 = 1++: Increment →let a = 5; a++; // 6--: Decrement →let b = 5; b--; // 4
2. Assignment Operators
=: Assign value →let x = 10;+=: Add & assign →x += 5; // x = x + 5-=: Subtract & assign →x -= 3; // x = x - 3*=: Multiply & assign →x *= 2; // x = x * 2/=: Divide & assign →x /= 2; // x = x / 2%=: Modulus & assign →x %= 3; // x = x % 3
3. Comparison Operators
==: Equal (value only) →5 == '5' → true===: Strict Equal (value & type) →5 === '5' → false!=: Not equal →5 != 3 → true!==: Strict not equal →5 !== '5' → true>: Greater than →10 > 5 → true<: Less than →3 < 7 → true>=: Greater than or equal →5 >= 5 → true<=: Less than or equal →4 <= 4 → true
4. Logical Operators
&&: AND → true if both are true →true && false → false||: OR → true if any is true →true || false → true!: NOT → inverts value →!true → false
5. Functions
Functions are **reusable blocks of code** that perform a specific task. They help you avoid repeating code and make your program more organized.
1. Basic Function
A simple function can just run code without returning anything.
// Example: basic function
function sayHello(){
console.log("Hello World!");
}
sayHello(); // Calls the function
Output: Hello World!
2. Function with Parameters
Parameters let you **pass values into a function**.
// Example: parameter
function greet(name){
console.log("Hello " + name + "!");
}
greet("Alice"); // Hello Alice!
greet("Bob"); // Hello Bob!
3. Function with Return Value
Functions can return a value that you can use later.
// Example: return value
function add(a, b){
return a + b;
}
let sum = add(5, 3);
console.log(sum); // 8
4. Arrow Functions (ES6)
A shorter way to write functions using the => syntax.
// Example: arrow function const multiply = (x, y) => x * y; console.log(multiply(4, 5)); // 20
6. Conditionals
Conditionals allow your code to **make decisions** based on certain conditions. JavaScript provides multiple ways to check conditions:
1. if Statement
The if statement executes a block of code **only if a condition is true**.
// Example: if
let age = 18;
if(age >= 18){
console.log("You are an adult");
}
Output: You are an adult
2. if...else Statement
The else block runs **if the condition is false**.
// Example: if...else
let age = 15;
if(age >= 18){
console.log("Adult");
}else{
console.log("Not an adult");
}
Output: Not an adult
3. if...else if...else Statement
Use else if to check **multiple conditions in order**.
// Example: multiple conditions
let score = 85;
if(score >= 90){
console.log("A Grade");
}else if(score >= 75){
console.log("B Grade");
}else if(score >= 50){
console.log("C Grade");
}else{
console.log("F Grade");
}
Output: B Grade
4. switch Statement
The switch statement checks a value against multiple cases. It's useful when you have **many
discrete options**.
// Example: switch
let day = 3;
switch(day){
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Another day");
}
Output: Wednesday
7. Loops
Loops are used to **repeat a block of code multiple times**. They save you from writing repetitive code manually. Common types in JavaScript:
forloopwhileloopdo...whileloopfor...ofloop (for arrays and iterable objects)
1. For Loop
The for loop repeats code a fixed number of times.
// Example: for loop
for(let i = 1; i <= 5; i++){
console.log("Count: " + i);
}
Output:
1, 2, 3, 4, 5
2. While Loop
The while loop repeats code as long as a condition is true.
// Example: while loop
let i = 1;
while(i <= 5){
console.log("Count: " + i);
i++;
}
3. Do...While Loop
Executes the code **at least once**, then continues if the condition is true.
// Example: do...while loop
let j = 1;
do {
console.log("Count: " + j);
j++;
} while(j <= 5);
4. For...of Loop
Useful for iterating over arrays or other iterable objects.
// Example: for...of loop
let fruits = ["Apple", "Banana", "Cherry"];
for(let fruit of fruits){
console.log(fruit);
}
Output:
Apple, Banana, Cherry
8. Arrays
An array is a collection of values stored in a single variable. Each value has an index, starting from 0. Arrays can store any type: numbers, strings, booleans, objects, or even other arrays.
1. Creating an Array
// Array of strings let fruits = ["Apple", "Banana", "Cherry"]; // Array of numbers let numbers = [10, 20, 30, 40]; // Array of mixed types let mixed = ["John", 25, true];
2. Accessing Array Elements
Access an element using its index:
console.log(fruits[0]); // Apple console.log(fruits[2]); // Cherry
3. Common Array Methods
push(value): Adds a value to the end →fruits.push("Mango")pop(): Removes the last value →fruits.pop()shift(): Removes the first value →fruits.shift()unshift(value): Adds a value to the start →fruits.unshift("Strawberry")length: Returns number of elements →fruits.lengthindexOf(value): Finds the index of a value →fruits.indexOf("Banana")includes(value): Checks if value exists →fruits.includes("Cherry") → true
4. Looping Through Arrays
// Using for loop
for(let i = 0; i < fruits.length; i++){
console.log(fruits[i]);
}
// Using for...of loop
for(let fruit of fruits){
console.log(fruit);
}
9. Objects
Objects are collections of **key-value pairs**.
They allow you to store and organize data more meaningfully than arrays.
Each key (property) has a value, and you can access values using obj.key or
obj["key"].
1. Creating an Object
// Object with properties
let person = {
name: "John",
age: 30,
isStudent: true
};
// Object with mixed types
let product = {
id: 101,
name: "Laptop",
price: 1200,
specs: {ram: "16GB", storage: "512GB"}
};
2. Accessing Properties
You can access values in two ways:
- Dot notation:
person.name→ "John" - Bracket notation:
person["age"]→ 30
3. Modifying Properties
person.age = 31; // Update value person["name"] = "Alice"; // Update using brackets person.country = "USA"; // Add new property delete person.isStudent; // Remove property
4. Object Methods
Objects can have functions as properties. These are called methods:
let person = {
name: "John",
age: 30,
greet: function() {
return "Hello, my name is " + this.name;
}
};
console.log(person.greet()); // "Hello, my name is John"
5. Looping Through Objects
Use for...in to iterate over keys:
for(let key in person){
console.log(key + ": " + person[key]);
}
10. DOM Manipulation
The DOM (Document Object Model) represents the HTML structure of a web page as a **tree of nodes**.
JavaScript can use the DOM to **access, modify, add, or remove HTML elements** dynamically.
Common methods: getElementById, querySelector, querySelectorAll.
Useful properties: innerHTML, textContent, style.
1. Accessing Elements
You can access elements by their ID or using CSS selectors:
2. Changing Content
You can update text or HTML inside an element using textContent or innerHTML.
3. Modifying Styles
Change CSS dynamically using the style property.
4. Adding and Removing Elements
You can create, append, or remove elements dynamically.
5. Interactive Example
Click a button to add a new paragraph dynamically.
11. Events
Events are **actions that happen in the browser**—like clicking a button, moving the mouse, typing on the
keyboard, or submitting a form.
JavaScript can **listen** for these events and **respond** with actions using functions.
The main method is: addEventListener(event, callback).
1. Click Event
Run code when a user clicks a button:
2. Mouse Events
Change element style on mouse hover:
3. Keyboard Events
Respond to key presses:
4. Input Events
Detect user input in a text box:
5. Form Submit Event
Prevent default form submission and validate data:
6. Event Delegation
Instead of attaching event listeners to each child element, attach it to a parent. Useful when creating elements dynamically.
12. Forms & Validation
Forms let users **input data** into your website. JavaScript can **access form fields, validate input**, and handle the submission to prevent unwanted behavior like page reloads.
1. Basic Form
Simple form with a text input and a submit button:
2. Form Validation
Check if the input is empty before submitting:
3. Multiple Input Validation
Validate username and email:
4. Real-time Input Validation
Check input as the user types:
5. Prevent Default Behavior
By default, submitting a form reloads the page. e.preventDefault() stops this.
6. Accessing Different Input Types
Forms can include checkboxes, radio buttons, and selects:
13. Simple Project
Create a counter that increases when a button is clicked.