How to Add Script (JavaScript) to Your Pages
Introduction to JavaScript and Its Role in Web Pages
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>
Page 2: Methods to Add JavaScript to Web Pages
There are three primary ways to include JavaScript in an HTML page:
1. Inline JavaScript
This method involves placing JavaScript code directly inside HTML elements using event attributes
such as onclick, onmouseover, etc.
Example:
<button onclick="alert('Hello!')">Click Me</button>
Advantages:
• Quick to implement.
• Useful for small scripts.
Disadvantages:
• Not recommended for complex code.
• Reduces readability and separation of concerns.
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.
Page 3: External JavaScript and Script Tag Attributes
3. External JavaScript
This is the most efficient and organized way to include JavaScript. You write JavaScript in a separate
.js file and link it to your HTML file.
Syntax:
<script src="script.js"></script>
Example:
• HTML file (index.html):
<!DOCTYPE html>
<html>
<head>
<script src="app.js"></script>
</head>
<body>
<button onclick="sayHello()">Greet</button>
</body>
</html>
• JavaScript file (app.js):
function sayHello() {
alert("Greetings from external JavaScript!");
}
Advantages:
• Code reusability across multiple pages.
• Clean separation of HTML and JavaScript.
• Better maintainability.
Script Tag Placement: Head vs. Body
Scripts can be placed in:
• <head>: Runs before the page is rendered (can delay loading).
• Just before </body>: Recommended for performance as it ensures the DOM is loaded before
the script runs.
Best Practice:
<body>
<!-- Page content -->
<script src="main.js"></script>
</body>
Page 4: Important Script Tag Attributes and Best Practices
Common <script> Tag Attributes
1. src – Specifies the path to the external JavaScript file.
<script src="script.js"></script>
2. type – Defines the MIME type (optional in modern HTML).
<script type="text/javascript" src="script.js"></script>
3. defer – Tells the browser to continue parsing HTML and execute the script after the document
has been fully parsed.
<script src="script.js" defer></script>
4. async – Script is executed asynchronously as soon as it’s available.
<script src="script.js" async></script>
Difference Between async and defer
Attribute When It Runs Execution Order
async As soon as it loads Order not guaranteed
defer After HTML is parsed Executes in order
Best Practice: Use defer for multiple script files to ensure the correct order of execution and no
interference with HTML rendering.
Page 5: DOM Manipulation and Event Handling
Accessing HTML Elements with JavaScript
You can use DOM methods to interact with HTML elements:
• document.getElementById()
• document.getElementsByClassName()
• document.querySelector()
Example:
<p id="demo">Original Text</p>
<script>
document.getElementById("demo").innerHTML = "Text Changed!";
</script>
Event Handling in JavaScript
JavaScript reacts to user actions using event listeners:
document.getElementById("btn").addEventListener("click", function() {
alert("Button clicked!");
});
HTML:
<button id="btn">Click</button>
Other events:
• onmouseover
• onkeydown
• onsubmit
• onchange
Form Validation Example
<form onsubmit="return validateForm()">
<input type="text" id="username">
<input type="submit" value="Submit">
</form>
<script>
function validateForm() {
var name = document.getElementById("username").value;
if (name === "") {
alert("Name must be filled out");
return false;
}
}
</script>
Variables and Data Types in JavaScript
Page 1: Introduction to Variables and Their Importance
What Are Variables?
In programming, variables are containers that store data values. In JavaScript, a variable is a named
memory location used to hold data that can be referenced and manipulated in a program.
Variables make it possible to write dynamic programs by allowing values to be stored, updated, and
used throughout the code. For example:
javascript
CopyEdit
var name = "Sangeetha";
In the above line, name is a variable that stores the string "Sangeetha".
Why Use Variables?
1. Data Storage: Hold values like numbers, text, or objects.
2. Reusability: Access and reuse data multiple times.
3. Dynamic Behavior: Change values as the program runs.
4. Readability: Makes code easier to understand.
5. Maintainability: Allows easy updates by changing one place.
Declaring Variables in JavaScript
JavaScript provides three keywords to declare variables:
• var (ES5 and earlier)
• let (ES6 and newer)
• const (ES6 and newer)
Page 2: Declaring Variables – var, let, and const
Using var
var is the traditional way of declaring variables in JavaScript. It has function scope, meaning it is
visible throughout the function in which it is declared.
Example:
javascript
CopyEdit
var age = 25;
• Can be redeclared and updated.
• Hoisted to the top of its scope.
Using let
let is a modern way to declare variables. It has block scope, meaning it is only accessible within the
block it is defined.
Example:
javascript
CopyEdit
let city = "Erode";
• Cannot be redeclared in the same scope.
• Can be updated.
Using const
const declares constant variables, which cannot be reassigned once declared. Like let, it also has
block scope.
Example:
javascript
CopyEdit
const pi = 3.14;
• Cannot be redeclared or updated.
• Useful for values that should not change.
Comparison Table
Feature var let const
Scope Function Block Block
Redeclaration Allowed Not allowed Not allowed
Reassignment Allowed Allowed Not allowed
Hoisting Yes Yes (TDZ) Yes (TDZ)
(TDZ = Temporal Dead Zone, means variable exists but not accessible until initialized.)
Page 3: JavaScript Data Types – Overview
What Are Data Types?
A data type defines the kind of data a variable can hold. JavaScript is a dynamically typed
language, which means variables do not need to be declared with a type—they can hold any data
type, and that type can change at runtime.
Two Main Categories
1. Primitive Data Types
2. Non-Primitive (Reference) Data Types
1. Primitive Data Types
These are basic data types and are immutable (cannot be altered once created).
• String
• Number
• Boolean
• Undefined
• Null
• BigInt (ES2020)
• Symbol (ES6)
2. Non-Primitive Data Types
These are reference types and include:
• Object
• Array
• Function
• Date
Page 4: Detailed Explanation of Primitive Data Types
1. String
Used to represent text. Defined inside quotes.
Example:
let name = "Sangeetha";
You can use:
• Single quotes ' '
• Double quotes " "
• Backticks (template literals) `` `
2. Number
Represents both integers and floating-point numbers.
Example:
let age = 21;
let score = 95.5;
3. Boolean
Has only two values: true or false.
Example:
let isPassed = true;
Used in condition checking and logical operations.
4. Undefined
A variable that has been declared but not assigned a value is undefined.
Example:
let status;
console.log(status); // undefined
5. Null
Represents the intentional absence of any value.
Example:
let data = null;
null is an object type in JavaScript (a known historical quirk).
Page 5: BigInt, Symbol, and Reference Types
6. BigInt
Used to represent large integers beyond the safe limit for numbers.
Example:
let bigNumber = 1234567890123456789012345678901234567890n;
Note the n at the end.
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
Page 6: Type Conversion, typeof, and Conclusion
Type Checking with typeof
The typeof operator helps to identify the data type of a variable.
Examples:
typeof "hello" // "string"
typeof 123 // "number"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" (JavaScript quirk)
typeof {} // "object"
typeof [] // "object"
Type Conversion in JavaScript
JavaScript automatically performs type coercion, but we can also convert types manually.
String to Number
let str = "123";
let num = Number(str); // 123
Number to String
let num = 456;
let str = String(num); // "456"
Boolean to Number
Number(true); // 1
Number(false); // 0
Statements and Operators in JavaScript
Introduction to Statements and Operators
What Are Statements?
In JavaScript, a statement is a complete instruction that performs an action. JavaScript programs are
composed of many such statements executed one after another.
Examples of JavaScript statements:
let x = 5; // Declaration statement
x = x + 1; // Assignment statement
console.log(x); // Function call statement
Statements tell the browser what to do and are usually followed by a semicolon (;) though not always
required.
Types of Statements
1. Declaration Statements – Declare variables.
2. Assignment Statements – Assign values to variables.
3. Conditional Statements – Make decisions (if, else, switch).
4. Looping Statements – Repeat blocks of code (for, while).
5. Function Statements – Declare functions.
6. Control Flow Statements – Change the order of execution (break, continue, return).
What Are Operators?
Operators are symbols or keywords used to perform operations on values (operands). They are the
building blocks of expressions and allow you to manipulate data and variables.
Example:
let result = 10 + 5; // + is an operator
JavaScript includes various categories of operators, each with a specific purpose.
Page 2: Categories of JavaScript Operators
JavaScript operators are grouped into the following categories:
1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Bitwise Operators
6. String Operators
7. Conditional (Ternary) Operator
8. Type Operators
9. Unary Operators
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
++ Increment x++ or ++x
-- Decrement x-- or --x
2. Assignment Operators
Used to assign values to variables.
Operator Description Example
= Assign x=5
+= Add and assign x += 2
-= Subtract and assign x -= 1
*= Multiply and assign x *= 3
/= Divide and assign x /= 2
%= Modulus and assign x %= 4
Page 3: Comparison and Logical Operators
3. Comparison Operators
Used to compare two values and return a Boolean (true or false).
Operator Description Example
== Equal to 5 == "5" → true
=== Strict equal to (type + value) 5 === "5" → false
!= Not equal to 5 != 6 → true
!== Strict not equal to 5 !== "5" → true
> Greater than 5 > 3 → true
< Less than 2 < 4 → true
>= Greater than or equal to 5 >= 5 → true
<= Less than or equal to 3 <= 5 → true
4. Logical Operators
Used to combine multiple conditions.
Operator Description Example
&& Logical AND true && false → false
` Logical OR True ‘ false -> True
! Logical NOT !true → false
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
>> Right shift
Example:
console.log(5 & 1); // Output: 1
7. Conditional (Ternary) Operator
This operator evaluates a condition and returns one of two values based on whether the condition is
true or false.
Syntax:
condition ? value_if_true : value_if_false;
Example:
let age = 20;
let access = (age >= 18) ? "Allowed" : "Denied";
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");
}
Loops with Operators
Operators are essential in loops to set conditions and increment values.
for Loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
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.
Control Structures in JavaScript
Introduction to Control Structures
What Are Control Structures?
Control structures are blocks of code that determine the flow of execution in a program. They allow a
program to:
• Make decisions
• Repeat actions
• Choose between different paths
These structures are crucial in any programming language as they add logic and decision-making to
your code.
Types of Control Structures
1. Conditional Control Structures
o if statement
o if...else statement
o if...else if...else statement
o switch statement
2. Looping Control Structures
o for loop
o while loop
o do...while loop
o for...in loop
o for...of loop
3. Jumping Control Structures
o break
o continue
o return
These structures enable dynamic behavior and automation in JavaScript programs.
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");
}
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");
}
Looping Control Structures
1. for Loop
Used to execute a block of code a specific number of times.
Syntax:
for (initialization; condition; increment) {
// code block
}
Example:
for (let i = 1; i <= 5; i++) {
console.log(i);
}
while and do...while Loops
2. while Loop
Executes the code as long as the condition is true.
Syntax:
while (condition) {
// block of code
}
Example:
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
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]);
}
for...of Loop and Jumping Statements
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);
}
Jumping Control Statements
1. break Statement
Exits a loop or switch prematurely.
Example:
for (let i = 1; i <= 10; i++) {
if (i === 5) break;
console.log(i);
}
// Output: 1 2 3 4
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"));
Summary of Control Structures
Type Structure Use Case
Conditional if, else, switch Making decisions
Looping for, while, do...while, for...in, for...of Repeating tasks
Jumping break, continue, return Controlling flow in loops/functions
Common Use Cases
• if...else: Form validations, decision making
• switch: Menu systems, role-based access
• for: Counting iterations
• while: Waiting for condition to become false
• for...in: Looping over object keys
• for...of: Looping over arrays or strings
Conditional Statements in JavaScript
Page 1: Introduction to Conditional Statements
What Are Conditional Statements?
Conditional statements are used to execute different actions based on different conditions. They
allow a program to make decisions, which is essential in developing logic-based and dynamic web
applications.
JavaScript supports several conditional statements:
• if statement
• if...else statement
• if...else if...else statement
• switch statement
• Ternary operator (conditional expression)
Purpose of Conditional Statements
Conditional statements control the flow of program execution by checking conditions that evaluate
to either true or false. Based on the result:
• Certain blocks of code may be executed
• Others may be skipped
This enables branching in the logic of a program.
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");
}
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);
Advantages of Conditional Statements
• Allow decision-making logic
• Increase flexibility of code
• Enable real-time data handling (e.g., form validation, access control)
Loop Statements in JavaScript
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.
Why Use Loops?
Loops are useful for:
• Repeating tasks
• Iterating over arrays or objects
• Performing operations until a condition is met
Types of Loops in JavaScript
1. for loop
2. while loop
3. do...while loop
4. for...in loop
5. for...of loop
Each type of loop has its own use case depending on the logic and data involved.
1. for Loop
Used to execute a block of code a specific number of times.
Syntax:
for (initialization; condition; increment) {
// code block
}
Example:
for (let i = 1; i <= 5; i++) {
console.log(i);
}
while and do...while Loops
2. while Loop
Executes the code as long as the condition is true.
Syntax:
while (condition) {
// block of code
}
Example:
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
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
Introduction to JavaScript Functions
What is a Function?
In JavaScript, a function is a set of statements that performs a task or calculates a value. It is executed
when it is called or invoked.
Syntax of a function:
function functionName(parameters) {
// Code to be executed
}
Example:
function greet(name) {
console.log("Hello, " + name);
}
greet("Sangeetha");
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.
PAGE 2: Types of Functions in JavaScript
JavaScript supports the following two main categories of functions:
1. Predefined Functions (Built-in / Inbuilt functions)
2. User-Defined Functions (Custom functions created by users)
Let’s explore each type in detail.
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.
Predefined Functions – Examples
A. String Functions
1. length – Returns the length of a string
let str = "JavaScript";
console.log(str.length); // Output: 10
2. toUpperCase() – Converts string to uppercase
let name = "sangeetha";
console.log(name.toUpperCase()); // Output: SANGEETHA
3. substring(start, end) – Returns part of a string
let text = "Data Science";
console.log(text.substring(0, 4)); // Output: Data
B. Array Functions
1. push() – Adds element to end of array
let fruits = ["Apple", "Banana"];
fruits.push("Orange");
2. pop() – Removes last element
fruits.pop();
3. length – Returns number of elements
console.log(fruits.length);
4. join() – Combines array elements into a string
console.log(fruits.join(", "));
More Predefined Functions
C. Number Functions
1. parseInt() – Converts string to integer
let num = parseInt("100");
2. toFixed() – Rounds a number to fixed decimal places
let price = 49.6789;
console.log(price.toFixed(2)); // 49.68
D. Date Functions
1. Date() – Gets current date and time
let currentDate = new Date();
console.log(currentDate);
2. getFullYear() – Gets the full year from a date
console.log(currentDate.getFullYear());
3. getMonth() – Gets month (0 to 11)
console.log(currentDate.getMonth());
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
Advanced User-Defined Function Types
A. Anonymous Function
A function without a name.
let greet = function(name) {
console.log("Hi " + name);
};
greet("Priya");
B. Arrow Function (ES6 Feature)
Compact way to define functions.
const multiply = (x, y) => x * y;
console.log(multiply(4, 5)); // Output: 20
C. Callback Function
A function passed into another function as an argument.
function processUserInput(callback) {
let name = "Kala";
callback(name);
}
processUserInput(function(name) {
console.log("Hello " + name);
});