Web unit 4
Web unit 4
What is JavaScript?
JavaScript is a powerful, lightweight, interpreted programming language primarily used to enhance
interactivity on websites. It is a client-side scripting language, meaning it is executed by the user's
browser rather than the web server. JavaScript enables dynamic content updates, form validation,
animations, real-time data fetching, and much more.
JavaScript is one of the three core technologies of the web, alongside HTML and CSS. While
HTML provides the structure and CSS handles presentation, JavaScript makes the web pages
interactive and functional.
Why Add JavaScript to Web Pages?
Adding JavaScript allows developers to:
• Create responsive user interfaces.
• Validate forms without reloading the page.
• Display or hide elements dynamically.
• Manipulate the Document Object Model (DOM).
• Handle events like clicks, mouseovers, and keyboard actions.
• Fetch data from servers using AJAX.
Basic Syntax of JavaScript
A simple JavaScript program may look like this:
<script>
alert("Welcome to My Website!");
</script>
2. Internal JavaScript
Internal JavaScript is written within <script> tags in the <head> or <body> section of the HTML
document.
Example:
<!DOCTYPE html>
<html>
<head>
<script>
function greet() {
alert("Hello from internal script!");
}
</script>
</head>
<body>
<button onclick="greet()">Click Here</button>
</body>
</html>
Use cases:
• When the script is specific to a single page.
• Easy to debug during development.
<script>
function validateForm() {
var name = document.getElementById("username").value;
if (name === "") {
alert("Name must be filled out");
return false;
}
}
</script>
Comparison Table
(TDZ = Temporal Dead Zone, means variable exists but not accessible until initialized.)
7. Symbol
Introduced in ES6, it represents a unique and immutable identifier.
Example:
let sym1 = Symbol("id");
let sym2 = Symbol("id");
console.log(sym1 === sym2); // false
Objects
An object is a collection of key-value pairs.
Example:
let student = {
name: "Priya",
age: 20,
course: "B.Sc. Data Science"
};
Access properties using:
• Dot notation: student.name
• Bracket notation: student["age"]
Arrays
Arrays are used to store multiple values in a single variable.
Example:
let colors = ["red", "green", "blue"];
Access elements by index: colors[0] // red
1. Arithmetic Operators
Used to perform mathematical calculations.
Operator Description Example
+ Addition 5+2=7
- Subtraction 5-2=3
* Multiplication 5 * 2 = 10
/ Division 5 / 2 = 2.5
% Modulus (Remainder) 5 % 2 = 1
2. Assignment Operators
Used to assign values to variables.
Operator Description Example
= Assign x=5
+= Add and assign x += 2
4. Logical Operators
Used to combine multiple conditions.
Example:
let age = 20;
if (age >= 18 && age <= 25) {
console.log("Eligible");
}
5. String Operators
In JavaScript, the + operator can also concatenate strings.
Examples:
let firstName = "Sangeetha";
let lastName = "Priya";
let fullName = firstName + " " + lastName; // "Sangeetha Priya"
Other String Methods (not operators but similar in use):
• str.length
• str.toUpperCase()
• str.includes("word")
6. Bitwise Operators
Bitwise operators work on binary representations of numbers.
Operator Description
& AND
` `
^ XOR
~ NOT
<< Left shift
Example:
console.log(5 & 1); // Output: 1
8. Type Operators
typeof
Returns the type of a variable.
typeof "hello"; // "string"
instanceof
Checks if an object is an instance of a constructor.
let arr = [];
console.log(arr instanceof Array); // true
Control Flow Statements Using Operators
Operators often combine with control statements for decision-making:
if...else Statement
let score = 75;
if (score >= 50) {
console.log("Pass");
} else {
console.log("Fail");
}
switch Statement
let day = "Monday";
switch(day) {
case "Monday":
console.log("Start of week");
break;
case "Friday":
console.log("End of week");
break;
default:
console.log("Midweek day");
}
Summary of Statements
• Statements control the execution flow of JavaScript programs.
• They include declarations, assignments, loops, conditionals, and functions.
• Every action in JavaScript is carried out using statements.
1. if Statement
Used to execute a block of code only if a specific condition is true.
Syntax:
if (condition) {
// code to execute
}
Example:
let age = 20;
if (age >= 18) {
console.log("Eligible to vote");
}
2. if...else Statement
Executes one block of code if the condition is true, another block if false.
Syntax:
if (condition) {
// block if true
} else {
// block if false
}
Example:
let marks = 35;
if (marks >= 40) {
console.log("Pass");
} else {
console.log("Fail");
}
if (condition1) {
// block 1
} else if (condition2) {
// block 2
} else {
// block 3
}
Example:
let grade = 85;
if (grade >= 90) {
console.log("A Grade");
} else if (grade >= 75) {
console.log("B Grade");
} else {
console.log("C Grade");
}
4. switch Statement
Used as a cleaner alternative to multiple if...else if...else statements when checking a single variable.
Syntax:
switch(expression) {
case value1:
// block 1
break;
case value2:
// block 2
break;
default:
// default block
}
Example:
let day = "Monday";
switch(day) {
case "Monday":
console.log("Start of week");
break;
case "Friday":
console.log("End of week");
break;
default:
console.log("Midweek day");
}
3. do...while Loop
Executes the block once before checking the condition, ensuring the code runs at least once.
Syntax:
do {
// block of code
} while (condition);
Example:
let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
4. for...in Loop
Used to iterate over object properties.
Syntax:
for (let key in object) {
// code block
}
Example:
let person = {name: "Sangeetha", age: 21};
for (let key in person) {
console.log(key + ": " + person[key]);
}
2. continue Statement
Skips the current iteration and continues with the next one.
Example:
for (let i = 1; i <= 5; i++) {
if (i === 3) continue;
console.log(i);
}
// Output: 1 2 4 5
3. return Statement
Exits from a function and optionally returns a value.
Example:
function greet(name) {
return "Hello " + name;
}
console.log(greet("Sangeetha"));
2. if...else Statement
Executes one block of code if the condition is true, another block if false.
Syntax:
if (condition) {
// block if true
} else {
// block if false
}
Example:
let marks = 35;
if (marks >= 40) {
console.log("Pass");
} else {
console.log("Fail");
}
3. if...else if...else Statement
Used for checking multiple conditions.
Syntax:
if (condition1) {
// block 1
} else if (condition2) {
// block 2
} else {
// block 3
}
Example:
let grade = 85;
if (grade >= 90) {
console.log("A Grade");
} else if (grade >= 75) {
console.log("B Grade");
} else {
console.log("C Grade");
}
4. switch Statement
Used as a cleaner alternative to multiple if...else if...else statements when checking a single variable.
Syntax:
switch(expression) {
case value1:
// block 1
break;
case value2:
// block 2
break;
default:
// default block
}
Example:
let day = "Monday";
switch(day) {
case "Monday":
console.log("Start of week");
break;
case "Friday":
console.log("End of week");
break;
default:
console.log("Midweek day");
}
5. Ternary Operator
Also called a conditional operator, it offers a short-hand for simple if...else.
Syntax:
condition ? expression_if_true : expression_if_false;
Example:
let age = 17;
let status = (age >= 18) ? "Adult" : "Minor";
console.log(status);
Introduction to Loops
What Are Loops?
Loops in JavaScript are control structures that allow you to execute a block of code repeatedly until
a specified condition is met. Instead of writing the same code multiple times, loops help in writing
efficient and concise code.
3. do...while Loop
Executes the block once before checking the condition, ensuring the code runs at least once.
Syntax:
do {
// block of code
} while (condition);
Example:
let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
4. for...in Loop
Used to iterate over object properties.
Syntax:
for (let key in object) {
// code block
}
Example:
let person = {name: "Sangeetha", age: 21};
for (let key in person) {
console.log(key + ": " + person[key]);
}
5. for...of Loop
Used to iterate over iterable objects like arrays or strings.
Syntax:
for (let value of iterable) {
// code block
}
Example:
let colors = ["red", "green", "blue"];
for (let color of colors) {
console.log(color);
}
JavaScript Functions
JavaScript functions are blocks of reusable code that perform a specific task. They help in structuring
code efficiently and improving readability and maintainability. Functions in JavaScript can be invoked
multiple times, allowing developers to avoid repetition and write modular code.
Functions are broadly categorized into two main types:
1. Predefined Functions (Inbuilt Library Functions)
2. User-defined Functions
Purpose of Functions
• Code Reusability: You can write a function once and use it multiple times.
• Modularity: Divide large programs into smaller functions.
• Abstraction: Hide complex details and expose only the necessary functionality.
• Debugging: Easier to locate and fix errors.
1. Predefined Functions
Predefined functions are built-in JavaScript functions that come with the language itself. These
functions are available for use without the need to create them manually. They are part of the
JavaScript Standard Library.
User-Defined Functions
User-defined functions are created by the programmer to perform specific tasks based on
requirements. These are not built-in but are custom written.
Syntax:
function functionName(parameters) {
// Function body
}
Example 1: Add Two Numbers
function add(a, b) {
return a + b;
}
console.log(add(10, 20)); // Output: 30
Example 2: Check Even or Odd
function checkEvenOdd(num) {
if (num % 2 === 0) {
return "Even";
} else {
return "Odd";
}
}
console.log(checkEvenOdd(5)); // Output: Odd