Unit 2: Scripting




Introduction to JavaScript

JavaScript (JS) is a client-side scripting language used to make web pages interactive and dynamic. It works with HTML and CSS to improve user experience.

Features of JavaScript

  • Lightweight and fast
  • Runs inside the browser
  • Object-based language
  • Supports event-driven programming
  • Platform independent

Uses of JavaScript

UseExample
Form validationChecking empty fields
Dynamic contentChanging text/images
User interactionButtons, alerts
CalculationsEMI, totals

Creating Variables in JavaScript

Variables are used to store data values.

Variable Keywords

KeywordDescription
varOld method, function-scoped
letBlock-scoped, recommended
constConstant value, cannot change

Example

let name = "Jay"; let age = 22; const pi = 3.14;

Rules for Variable Names

  • Must start with a letter, _, or $
  • Cannot use keywords
  • Case-sensitive

Creating Functions in JavaScript

A function is a block of code that performs a specific task and can be reused.

Function Syntax

function functionName() { // code }

Example

function greet() { alert("Welcome to JavaScript"); }

Function with Parameters

function add(a, b) { return a + b; }

UI Events in JavaScript

UI Events occur when users interact with the webpage.

Common UI Events

EventDescription
onclickMouse click
onmouseoverMouse over element
onmouseoutMouse leaves
onchangeInput value changes
onkeyupKey released
onsubmitForm submission

Example

<button onclick="greet()">Click Me</button>

Returning Data from Functions

Functions can return values using the return keyword.

Example

function square(x) { return x * x; } let result = square(5);

Key Points

  • return sends data back to the caller
  • Code after return does not execute
  • One function can return only one value

Working with Conditions

Conditional statements allow decision-making in programs.

Types of Conditional Statements

1. if Statement

if (age >= 18) { alert("Eligible to vote"); }

2. if-else Statement

if (marks >= 40) { alert("Pass"); } else { alert("Fail"); }

3. else-if Ladder

if (marks >= 75) { grade = "A"; } else if (marks >= 60) { grade = "B"; } else { grade = "C"; }

4. switch Statement

switch(day) { case 1: dayName = "Monday"; break; case 2: dayName = "Tuesday"; break; default: dayName = "Invalid"; }

Comparison Table

ConceptPurpose
VariablesStore data
FunctionsReusable logic
EventsUser interaction
ConditionsDecision making

Summary

  • JavaScript adds interactivity to web pages
  • Variables store values using var, let, const
  • Functions make code reusable
  • Events respond to user actions
  • Conditions control program flow

Looping in JavaScript

Loops are used to execute a block of code repeatedly until a condition is satisfied.

Types of Loops in JavaScript

1. for Loop

Used when the number of iterations is known.

for (let i = 1; i <= 5; i++) { console.log(i); }

2. while Loop

Executes as long as the condition is true.

let i = 1; while (i <= 5) { console.log(i); i++; }

3. do-while Loop

Executes at least once, even if the condition is false.

let i = 1; do { console.log(i); i++; } while (i <= 5);

4. for...of Loop

Used to iterate over arrays.

let numbers = [10, 20, 30]; for (let num of numbers) { console.log(num); }

Loop Control Statements

StatementPurpose
breakStops loop execution
continueSkips current iteration

Block Scope Variables

Block scope means variables are accessible only within the block { } in which they are declared.

Block-Scoped Keywords

KeywordScope
letBlock scope
constBlock scope
varFunction scope

Example

if (true) { let x = 10; const y = 20; } // x and y cannot be accessed here

Advantages of Block Scope

  • Prevents variable conflicts
  • Improves code security
  • Easier debugging

Working with Objects

In JavaScript, an object is a collection of key-value pairs.

Example Object

let student = { name: "Jay", age: 22, course: "MCA" };

Accessing Object Properties

student.name; student["age"];

Creating Object using Object Literals

Object literals are the simplest way to create objects.

Syntax

let objectName = { property1: value1, property2: value2 };

Example with Method

let employee = { id: 101, name: "Amit", salary: 30000, display: function() { return this.name + " earns " + this.salary; } };

Advantages of Object Literals

  • Easy to create
  • Less code
  • Readable structure

Manipulating DOM Elements with JavaScript

DOM (Document Object Model) represents the structure of an HTML document as objects.

Common DOM Methods

MethodUse
getElementById()Select element by ID
getElementsByClassName()Select by class
getElementsByTagName()Select by tag
querySelector()Select first match
querySelectorAll()Select all matches

Changing Content

document.getElementById("demo").innerHTML = "Hello JavaScript";

Changing Style

document.getElementById("demo").style.color = "blue";

Handling Events with DOM

document.getElementById("btn").onclick = function() { alert("Button Clicked"); };

DOM Manipulation Tasks

TaskMethod
Change textinnerHTML
Change stylestyle.property
Add elementcreateElement()
Remove elementremove()

Summary Table

TopicKey Concept
LoopsRepetition
Block ScopeSecure variables
ObjectsKey-value data
Object LiteralsEasy object creation
DOMHTML manipulation