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 .js file linked via <script src="file.js"></script>.

Example: Inline JS
<button onclick="alert('Hello World!')">Click Me</button>

3. Variables & Data Types

Variables store data. Use let or const (avoid var). Common data types: String, Number, Boolean, null, undefined.

Example
let name = "John"; const age = 25; let isStudent = true; console.log(name, age, isStudent);

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
Example
// Arithmetic let a = 10, b = 3; console.log("a + b =", a + b); console.log("a - b =", a - b); console.log("a * b =", a * b); console.log("a / b =", a / b); console.log("a % b =", a % b); // Assignment let x = 5; x += 2; // x = 7 console.log("x after x += 2:", x); // Comparison console.log("10 == '10' ?", 10 == '10'); console.log("10 === '10' ?", 10 === '10'); console.log("10 != 5 ?", 10 != 5); // Logical console.log("true && false =", true && false); console.log("true || false =", true || false); console.log("!true =", !true);

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
  
Interactive Example
function greet(name){ return "Hello " + name; } console.log(greet("Alice")); console.log(greet("Bob"));

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

Interactive Example
let score = 85; if(score >= 90){ console.log("A Grade"); }else if(score >= 75){ console.log("B Grade"); }else{ console.log("C Grade"); }

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:

  • for loop
  • while loop
  • do...while loop
  • for...of loop (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

Interactive Example
for(let i = 1; i <= 5; i++){ console.log("Count: " + i); }

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.length
  • indexOf(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);
}
  
Interactive Example
let fruits = ["Apple", "Banana", "Cherry"]; console.log("Original Array:", fruits); // Add a new fruit fruits.push("Mango"); console.log("After push:", fruits); // Remove the last fruit fruits.pop(); console.log("After pop:", fruits); // Check length console.log("Array length:", fruits.length); // Loop through array for(let fruit of fruits){ console.log("Fruit:", 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]);
}
  
Interactive Example
let person = { name: "John", age: 30, isStudent: true, greet: function() { return "Hello, " + this.name; } }; // Access properties console.log("Name:", person.name); console.log("Age:", person["age"]); // Modify properties person.age = 31; person.country = "USA"; // Loop through object for(let key in person){ console.log(key + ":", person[key]); } // Call object method console.log(person.greet());

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:

<h3 id="title">My Page</h3> <script> let title = document.getElementById("title"); console.log(title.textContent); // Outputs: My Page let firstHeader = document.querySelector("h3"); console.log(firstHeader.innerHTML); // Outputs: My Page </script>

2. Changing Content

You can update text or HTML inside an element using textContent or innerHTML.

let para = document.createElement("p"); para.textContent = "Hello using textContent!"; document.body.appendChild(para); // Using innerHTML to add HTML let box = document.createElement("div"); box.innerHTML = "<b>Bold Text using innerHTML</b>"; document.body.appendChild(box);

3. Modifying Styles

Change CSS dynamically using the style property.

let heading = document.createElement("h2"); heading.textContent = "Styled Heading"; heading.style.color = "white"; heading.style.backgroundColor = "blue"; heading.style.padding = "10px"; document.body.appendChild(heading);

4. Adding and Removing Elements

You can create, append, or remove elements dynamically.

let newPara = document.createElement("p"); newPara.textContent = "This paragraph can be removed."; document.body.appendChild(newPara); // Remove after 3 seconds setTimeout(() => { document.body.removeChild(newPara); }, 3000);

5. Interactive Example

Click a button to add a new paragraph dynamically.

let btn = document.createElement("button"); btn.textContent = "Add Paragraph"; document.body.appendChild(btn); btn.addEventListener("click", () => { let p = document.createElement("p"); p.textContent = "New paragraph added!"; document.body.appendChild(p); });

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:

let btn = document.createElement("button"); btn.textContent = "Click Me"; document.body.appendChild(btn); btn.addEventListener("click", () => { alert("Button clicked!"); });

2. Mouse Events

Change element style on mouse hover:

let box = document.createElement("div"); box.textContent = "Hover over me!"; box.style.width = "200px"; box.style.height = "50px"; box.style.backgroundColor = "lightblue"; box.style.textAlign = "center"; box.style.lineHeight = "50px"; box.style.marginTop = "10px"; document.body.appendChild(box); box.addEventListener("mouseenter", () => { box.style.backgroundColor = "skyblue"; }); box.addEventListener("mouseleave", () => { box.style.backgroundColor = "lightblue"; });

3. Keyboard Events

Respond to key presses:

document.body.addEventListener("keydown", (event) => { console.log("Key pressed:", event.key); });

4. Input Events

Detect user input in a text box:

let input = document.createElement("input"); input.placeholder = "Type something..."; document.body.appendChild(input); input.addEventListener("input", () => { console.log("Current value:", input.value); });

5. Form Submit Event

Prevent default form submission and validate data:

let form = document.createElement("form"); let username = document.createElement("input"); username.placeholder = "Enter username"; let submit = document.createElement("input"); submit.type = "submit"; submit.value = "Submit"; form.appendChild(username); form.appendChild(submit); document.body.appendChild(form); form.addEventListener("submit", (e) => { e.preventDefault(); // Prevent page reload if(username.value === "") alert("Please enter username!"); else alert("Hello " + username.value + "!"); });

6. Event Delegation

Instead of attaching event listeners to each child element, attach it to a parent. Useful when creating elements dynamically.

let list = document.createElement("ul"); document.body.appendChild(list); for(let i=1; i<=3; i++){ let li=document.createElement("li"); li.textContent="Item " + i; list.appendChild(li); } // Attach event to parent (ul) list.addEventListener("click", (e)=> { if(e.target.tagName === "LI"){ alert("You clicked: " + e.target.textContent); } });

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:

<form id="myForm"> <input type="text" id="username" placeholder="Enter username"> <input type="submit" value="Submit"> </form> <script> document.getElementById("myForm").addEventListener("submit", function(e){ e.preventDefault(); // Prevent page reload let name = document.getElementById("username").value; alert("Hello " + name); }); </script>

2. Form Validation

Check if the input is empty before submitting:

let form = document.createElement("form"); let username = document.createElement("input"); username.placeholder = "Enter username"; let submit = document.createElement("input"); submit.type = "submit"; submit.value = "Submit"; form.appendChild(username); form.appendChild(submit); document.body.appendChild(form); form.addEventListener("submit", (e) => { e.preventDefault(); if(username.value === "") { alert("Please enter a username!"); } else { alert("Hello " + username.value + "!"); } });

3. Multiple Input Validation

Validate username and email:

let form2 = document.createElement("form"); let username2 = document.createElement("input"); username2.placeholder = "Username"; let email = document.createElement("input"); email.placeholder = "Email"; email.type = "email"; let submit2 = document.createElement("input"); submit2.type = "submit"; submit2.value = "Submit"; form2.append(username2, email, submit2); document.body.appendChild(form2); form2.addEventListener("submit", (e) => { e.preventDefault(); if(username2.value === "" || email.value === ""){ alert("Please fill all fields!"); } else { alert("Username: " + username2.value + "\nEmail: " + email.value); } });

4. Real-time Input Validation

Check input as the user types:

let inputBox = document.createElement("input"); inputBox.placeholder = "Type at least 5 chars"; document.body.appendChild(inputBox); let message = document.createElement("p"); document.body.appendChild(message); inputBox.addEventListener("input", () => { if(inputBox.value.length < 5){ message.textContent="Too short!" ; message.style.color="red" ; } else { message.textContent="Looks good!" ; message.style.color="green" ; } });

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:

let form3 = document.createElement("form"); let checkbox = document.createElement("input"); checkbox.type = "checkbox"; checkbox.id = "subscribe"; let label = document.createElement("label"); label.textContent = "Subscribe to newsletter"; label.htmlFor = "subscribe"; let select = document.createElement("select"); let option1 = document.createElement("option"); option1.value = "male"; option1.textContent = "Male"; let option2 = document.createElement("option"); option2.value = "female"; option2.textContent = "Female"; select.append(option1, option2); let submit3 = document.createElement("input"); submit3.type = "submit"; submit3.value = "Submit"; form3.append(checkbox, label, select, submit3); document.body.appendChild(form3); form3.addEventListener("submit", (e) => { e.preventDefault(); alert( "Subscribed: " + checkbox.checked + "\nGender: " + select.value ); });

13. Simple Project

Create a counter that increases when a button is clicked.

Example
<button id="counterBtn">Click me</button> <span id="count">0</span> <script> let count = 0; document.getElementById("counterBtn").addEventListener("click", function(){ count++; document.getElementById("count").textContent = count; }); </script>