Revision: Unit II - JavaScript

BMC201 - Web Technology

Mr. Prashant Kumar Nag

2026-03-05

Revision Session

Unit II: JavaScript

Weeks 6-7 | Mid-Semester Exam Preparation
BMC201 - Web Technology
Mr. Prashant Kumar Nag, Assistant Professor

Unit II: Complete Coverage


Topics Include:

  1. JavaScript Variables & Data Types
  2. Functions & Events
  3. Conditional Statements & Looping
  4. Objects & Scope
  5. Arrow Functions & Callbacks
  6. DOM Manipulation & Array Methods
  7. Form Validation
  8. ES6+ Features (Template Literals, Destructuring, Spread)

What is JavaScript?


  • Client-side programming language
  • Runs in the browser
  • Makes web pages interactive
  • Can manipulate HTML and CSS
  • Handles events (clicks, input, etc.)
  • Dynamically typed language

Including JavaScript in HTML


<!-- Inline -->
<button onclick="alert('Clicked!')">Click Me</button>

<!-- Internal -->
<script>
  console.log("Hello World");
</script>

<!-- External (Recommended) -->
<script src="script.js"></script>

Place <script> tag before closing </body> tag

JavaScript Variables


let age = 25;           // Reassignable, block-scoped
const pi = 3.14;        // Not reassignable, block-scoped
var old = "avoid";      // Function-scoped (old style)

age = 26;               // OK
pi = 3.15;              // Error!

Best Practice: Use const by default, let when needed

JavaScript Data Types


const name = "Amit";           // String
const age = 22;                // Number
const isActive = true;         // Boolean
const items = [1, 2, 3];       // Array
const user = {name: "Amit"};   // Object
let nothing = null;            // Null
let notDefined;                // Undefined
const id = Symbol("id");       // Symbol (ES6)

Checking Data Types


typeof "hello"        // "string"
typeof 42             // "number"
typeof true           // "boolean"
typeof []             // "object" (arrays are objects)
typeof null           // "object" (quirk in JS)

String Operations


const str = "Hello World";
const str2 = 'Single quotes work too';

// Methods
str.length              // 11
str.toUpperCase()       // "HELLO WORLD"
str.substring(0, 5)     // "Hello"

// Concatenation
const greeting = "Hello" + " " + "World";
const name = "Amit";
const message = `Hello, ${name}!`;  // Template literal

Number Operations


// Arithmetic
const sum = 10 + 5;       // 15
const diff = 10 - 5;      // 5
const product = 10 * 5;   // 50
const quotient = 10 / 5;  // 2
const remainder = 10 % 3; // 1

// Methods
Math.round(4.7);    // 5
Math.floor(4.7);    // 4
Math.random();      // 0 to 1

Arrays: Basics


const nums = [1, 2, 3, 4, 5];
const mixed = [1, "two", true, [3, 4]];

nums[0];              // 1 (access)
nums.length;          // 5
nums.push(6);         // Add to end: [1,2,3,4,5,6]
nums.pop();           // Remove from end: [1,2,3,4,5]

Array Methods


const arr = [1, 2, 3, 4, 5];
arr.map(x => x * 2);              // [2, 4, 6, 8, 10]
arr.filter(x => x > 2);           // [3, 4, 5]
arr.reduce((sum, x) => sum + x, 0); // 15
arr.find(x => x > 3);             // 4
arr.includes(3);                  // true
arr.forEach(x => console.log(x)); // Print each

Functions


// Function declaration
function greet(name) {
  return `Hello, ${name}`;
}

// Function expression
const greetExpr = function(name) {
  return `Hello, ${name}`;
};

// Calling
greet("Priya");  // "Hello, Priya"

Arrow Functions


const add = (a, b) => a + b;
const square = x => x * x;
const greet = () => "Hello";
const fullName = (first, last) => {
  return `${first} ${last}`;
};
  • If one parameter, parentheses optional
  • If single expression, return and {} optional

Default Parameters


function greet(name = "Guest") {
  return `Hello, ${name}`;
}

greet();           // "Hello, Guest"
greet("Neha");     // "Hello, Neha"

Conditional Statements


const marks = 85;

if (marks >= 90) {
  console.log("Grade A");
} else if (marks >= 60) {
  console.log("Grade B");
} else {
  console.log("Grade C");
}

// Ternary operator
const result = marks >= 60 ? "Pass" : "Fail";

Comparison Operators


5 == "5"    // true (type coercion)
5 === "5"   // false (strict equality)

10 != 5     // true
10 !== 5    // true (strict inequality)

10 > 5      // true
10 < 5      // false
10 >= 10    // true
10 <= 9     // false

Always use === and !== for strict comparison

Logical Operators


true && true     // true (AND)
true || false    // true (OR)
!true            // false (NOT)

const canVote = age >= 18 && isCitizen;
const hasAccess = isAdmin || isModerator;

Switch Statement


const day = "Monday";
switch (day) {
  case "Monday":
    console.log("Start of week");
    break;
  case "Friday":
    console.log("Weekend soon");
    break;
  default:
    console.log("Regular day");
}

For Loop


for (let i = 0; i < 5; i++) {
  console.log(i);  // 0, 1, 2, 3, 4
}

for (let i = 10; i > 0; i--) {
  console.log(i);  // 10, 9, 8, ..., 1
}

While & Do-While Loops


let count = 0;
while (count < 3) {
  console.log(count++);  // 0, 1, 2
}

let n = 0;
do {
  console.log(n++);  // 0, 1, 2
} while (n < 3);

do...while runs at least once

for…of and for…in


// for...of (arrays)
const nums = [10, 20, 30];
for (const num of nums) {
  console.log(num);  // 10, 20, 30
}

// for...in (objects)
const user = {name: "Amit", age: 22};
for (const key in user) {
  console.log(key, user[key]);  // name Amit, age 22
}

break and continue


for (let i = 1; i <= 10; i++) {
  if (i === 4) continue;  // Skip 4
  if (i === 8) break;     // Stop at 8
  console.log(i);         // 1, 2, 3, 5, 6, 7
}

JavaScript Objects


const student = {
  name: "Neha",
  age: 21,
  course: "CSE",
  greet: function() { return `Hi, ${this.name}`; }
};

console.log(student.name);     // "Neha"
console.log(student["age"]);   // 21
student.greet();               // "Hi, Neha"

Object Operations


// Add property
student.email = "neha@example.com";

// Update property
student.age = 22;

// Delete property
delete student.course;

// Check property
"name" in student;  // true

Variable Scope


// Global scope
const globalVar = "accessible everywhere";

// Function scope
function myFunc() {
  const localVar = "only inside function";
}

// Block scope (let/const)
if (true) {
  let blockVar = "only inside block";
}

Document Object Model (DOM)


  • Tree-like representation of HTML
  • JavaScript can read and modify DOM
  • Changes update the page in real-time

Root: document object

Common methods: - Select elements - Modify content - Change styles - Add/remove elements

Selecting DOM Elements


document.getElementById('header');
document.querySelector('.navbar');
document.querySelectorAll('p');
document.getElementsByClassName('item');
  • querySelector: returns first match
  • querySelectorAll: returns all matches (NodeList)

Modifying Content


const para = document.querySelector('p');

para.textContent = "New text";
para.innerHTML = "<strong>Bold text</strong>";

console.log(para.textContent);  // Plain text
console.log(para.innerHTML);    // HTML markup

Modifying Attributes


const img = document.querySelector('img');

img.src = 'photo.jpg';
img.alt = 'Description';
img.setAttribute('width', '300');

Modifying Styles


const box = document.querySelector('.box');

box.style.color = 'blue';
box.style.backgroundColor = 'lightgray';
box.style.fontSize = '18px';

CSS properties become camelCase in JavaScript

Working with Classes


const btn = document.querySelector('button');

btn.classList.add('active');
btn.classList.remove('disabled');
btn.classList.toggle('highlight');
btn.classList.contains('active');  // true/false

Creating & Removing Elements


const newDiv = document.createElement('div');
newDiv.textContent = 'Hello!';
newDiv.classList.add('message');

const parent = document.querySelector('#container');
parent.appendChild(newDiv);

// Remove
newDiv.remove();

Event Handling


const btn = document.querySelector('button');
btn.addEventListener('click', function() {
  alert('Button clicked!');
});

Common events: - click, dblclick - submit, change, input - keydown, keyup - mouseenter, mouseleave - load, DOMContentLoaded

Event Object


btn.addEventListener('click', function(event) {
  console.log(event.target);     // Element clicked
  console.log(event.type);       // "click"
  event.preventDefault();        // Prevent default action
});

Form Validation


const form = document.querySelector('form');

form.addEventListener('submit', function(e) {
  e.preventDefault();
  if (validateForm()) {
    console.log("Form is valid");
  }
});

Regular Expression Validation


function isValidEmail(email) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

function isValidPhone(phone) {
  return /^[0-9]{10}$/.test(phone);
}

if (isValidEmail("user@example.com")) {
  console.log("Valid email");
}

Template Literals (ES6)


const name = "Priya";
const age = 22;
const message = `Hello, ${name}! You are ${age} years old.`;

// Multi-line strings
const html = `
  <div>${name}</div>
  <p>Age: ${age}</p>
`;

Destructuring (ES6)


// Array destructuring
const [a, b, c] = [1, 2, 3];

// Object destructuring
const {name, age} = {name: "Amit", age: 22};

// With renaming
const {name: userName, age: userAge} = user;

Spread Operator (ES6)


// Arrays
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];  // [1, 2, 3, 4, 5]

// Objects
const user = {name: "Raj", age: 25};
const updated = {...user, age: 26};

// Function arguments
Math.max(...[1, 5, 3, 9, 2]);  // 9

Practice Question 1


Q: Write a function calculateGrade(marks) that: - Takes marks (0-100) - Returns “A” for ≥90, “B” for ≥60, “C” for <60 - Validates input (must be number between 0-100)

console.log(calculateGrade(85));   // "B"
console.log(calculateGrade(95));   // "A"
console.log(calculateGrade(150));  // "Invalid"

Practice Question 2


Q: Given an array of student objects:

const students = [
  {name: "Amit", marks: 85},
  {name: "Neha", marks: 92},
  {name: "Raj", marks: 78}
];
  1. Filter students with marks > 80
  2. Get array of their names
  3. Display names as comma-separated string

Expected output: “Amit, Neha”

Practice Question 3


Q: Create a webpage with: - Button with id “changeBtn” - Paragraph with id “text”

Write JavaScript to: 1. When button is clicked, change paragraph text to “Text Changed!” 2. Change button background color to green 3. Add class “active” to button 4. Show alert with current time

Practice Question 4


Q: Create a form validator that checks: - Email format (must contain @ and .) - Phone (exactly 10 digits) - Password (minimum 8 characters)

Show specific error message for each invalid field in red text below the input.

Prevent form submission if any field is invalid.

Common JavaScript Mistakes


  • Using = instead of === for comparison
  • Forgetting const/let keyword
  • Not preventing default form submission
  • Modifying array while iterating
  • Incorrect arrow function syntax
  • Missing return in functions
  • Wrong event handler syntax
  • Not checking for null/undefined

Debugging Tips


console.log(variable);           // Print value
console.error("Error message");  // Show error
console.table(arrayOfObjects);   // Table format
debugger;                        // Pause execution

Browser DevTools: - F12 to open - Console tab for errors - Elements tab for DOM inspection

Key Exam Topics - Unit II


  1. Variables (let, const) and data types
  2. Functions (regular, arrow, default params)
  3. Conditionals (if/else, switch, ternary)
  4. Loops (for, while, forEach)
  5. Arrays and array methods
  6. Objects and object operations
  7. DOM selection and manipulation
  8. Event handling
  9. Form validation with regex
  10. ES6 features (template literals, destructuring, spread)

Study Checklist


✓ Can declare variables with let/const
✓ Know all data types and typeof
✓ Can write functions (both regular and arrow)
✓ Understand if/else and switch statements
✓ Can write all loop types
✓ Know array methods (map, filter, reduce)
✓ Can create and manipulate objects
✓ Can select and modify DOM elements
✓ Know how to handle events
✓ Can validate forms with JavaScript and regex
✓ Understand template literals and destructuring

Final Practice Tips


  1. Write code daily - Practice typing, not just reading
  2. Use browser console - Test small code snippets
  3. Debug errors - Learn to read error messages
  4. Build small projects - Todo list, calculator, form
  5. Review labs - Go through all lab exercises again
  6. Time yourself - Practice under exam conditions
  7. Explain concepts - Teach someone else
  8. Test edge cases - Empty inputs, 0, negative numbers

You’re Ready for the Exam!

Mid-Semester Examination: March 10-14, 2026