Web Technology JavaScript Notes 49025828 2025 06-24-17 27
Web Technology JavaScript Notes 49025828 2025 06-24-17 27
JavaScript
JavaScript is a high-level, interpreted programming language primarily used to create interactive and dynamic content on
web pages. It is one of the core technologies of the World Wide Web, alongside HTML and CSS.
Features of Javascript:
1. Lightweight and interpreted: JavaScript runs directly in the browser without needing compilation, making it fast and
efficient.
2. Object-oriented: It uses objects (with properties and methods) to organize and manipulate data.
3. Cross-platform: JavaScript works on all devices and operating systems that support web browsers.
4. Dynamically typed: You don’t need to declare variable types; they are determined at runtime.
5. Event-driven and asynchronous capabilities: It reacts to user actions (like clicks) and handles tasks without blocking
the rest of the code.
JavaScript is used for tasks like form validation, creating animations, handling user events, and more.
<!-- Example: Simple HTML with JavaScript -->
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Example</title>
</head>
<body>
<h1>Welcome to JavaScript!</h1>
<script>
console.log("Hello, World!");
</script>
</body>
</html>
JavaScript Syntax
Variables and Constants
JavaScript provides three ways to declare variables: var, let, and const. Each has distinct characteristics and use cases.
Comparison of var, let, and const
Feature var let const
Scope Function-scoped Block-scoped Block-scoped if (true)
{ var a = 10; // Function-scoped
let b = 20; // Block-scoped
const c = 30; // Block-scoped }
console.log(a); // Output: 10
console.log(b); // Error: b is not defined
console.log(c); // Error: c is not defined
Hoisting Hoisted to the Hoisted to the top, Hoisted to the console.log(x); // Output: undefined (var is
top, initialized but not initialized. top, but not hoisted)
as undefined. initialized. console.log(y); // Error: Cannot access 'y' before
initialization
console.log(z); // Error: Cannot access 'z' before
initialization
var x = 10;
let y = 20;
const z = 30;
Reassignment Allowed Allowed Not allowed var x = 10;
x = 15; // Allowed
console.log(x); // Output: 15
let y = 20;
y = 25; // Allowed
console.log(y); // Output: 25
const z = 30;
z = 35; // Error: Assignment to constant variable
console.log(z); // Output: 30
Example:
let num1 = 42; // Integer
let num2 = 3.14; // Floating-point number
let infinityVal = 1 / 0; // Infinity
let nanVal = "abc" / 2; // NaN
console.log(num1, num2, infinityVal, nanVal);
2. String
Represents textual data enclosed in single ('), double ("), or backticks (`).
Example:
let singleQuote = 'Hello';
let doubleQuote = "World";
let templateLiteral = `Hello, ${singleQuote}`;
console.log(singleQuote, doubleQuote, templateLiteral);
3. Boolean
Represents logical values: true or false.
Example:
let isJavaScriptFun = true;
let isJavaScriptHard = false;
console.log(isJavaScriptFun, isJavaScriptHard);
Example:
let undefinedVar;
console.log(undefinedVar); // undefined
5. Null
Represents an intentional absence of value.
Example:
let nullVar = null;
console.log(nullVar); // null
Example:
let sym1 = Symbol("id");
let sym2 = Symbol("id");
console.log(sym1 === sym2); // false
Example:
let bigIntVal = 1234567890123456789012345678901234567890n;
console.log(bigIntVal);
Example:
let obj = { name: "Alice", age: 25 };
let arr = [1, 2, 3];
let func = function () { return "Hello"; };
console.log(obj, arr, func());
Important Points
1. Type Checking: Use typeof to check the type of a variable.
Example: console.log(typeof 42); // "number"
console.log(typeof "Hello"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (legacy bug)
console.log(typeof Symbol("id")); // "symbol"
console.log(typeof 123n); // "bigint"
console.log(typeof {}); // "object"
console.log(typeof NaN); // number
Subscribe Infeepedia youtube channel for computer science competitive exams
Download Infeepedia app and call or wapp on 8004391758
Web Tech JavaScript Infeepedia By: Infee Tripathi
2. Null vs Undefined:
undefined: A variable is declared but not assigned a value.
null: Explicitly set to indicate "no value."
Operators in JavaScript
Operators in JavaScript are used to perform operations on values and variables. They are categorized into several types
based on their functionality.
1. Arithmetic Operators
It is used to perform mathematical operations.
Operator Description Example Result
+ Addition 5+2 7
- Subtraction 5-2 3
* Multiplication 5*2 10
/ Division 5/2 2.5
% Modulus (Remainder) 5%2 1
** Exponentiation 5 ** 2 25
++ Increment let x = 5; x++ 6
-- Decrement let x = 5; x-- 4
2. Assignment Operators
It is used to assign values to variables.
Operator Description Example Result
= Assign x=5 x=5
+= Add and assign x += 2 x=x+2
-= Subtract and assign x -= 2 x=x-2
*= Multiply and assign x *= 2 x=x*2
/= Divide and assign x /= 2 x=x/2
%= Modulus and assign x %= 2 x=x%2
**= Exponentiation and assign x **= 2 x = x ** 2
3. Comparison Operators
It is used to compare two values.
Operator Description Example Result
== Equal to 5 == '5' true
=== Strict equal to 5 === '5' false
!= Not equal to 5 != '5' false
!== Strict not equal to 5 !== '5' true
> Greater than 5>2 true
< Less than 5<2 false
>= Greater than or equal to 5 >= 5 true
<= Less than or equal to 5 <= 2 false
5. Bitwise Operators
It operate on binary representations of numbers.
Operator Description Example Result
& AND 5&1 1
` ` OR `5
^ XOR 5^1 4
~ NOT ~5 -6
<< Left shift 5 << 1 10
>> Right shift 5 >> 1 2
>>> Zero-fill right shift 5 >>> 1 2
6. String Operators
It used to manipulate strings.
Operator Description Example Result
+ Concatenation 'Hello' + 'World' 'HelloWorld'
+= Concatenate and assign let x = 'Hi'; x += '!' 'Hi!'
7. Type Operators
It used to check or convert data types.
Operator Description Example Result
typeof Returns the type of a value typeof 42 'number'
instanceof Checks if an object is an instance of a class obj instanceof Object true
8. Ternary Operator
Shorthand for conditional expressions.
Operator Description Example Result
?: Conditional operator Ex1: let x= 5 > 2 ? 'Yes' : 'No' Ex1: 'Yes'
Ex2:
let age = 18; Ex2: Adult
let result = age >= 18 ? "Adult" : "Minor";
console.log(result); // "Adult"
9. Other Operators
Operator Description Example Result
, Comma operator let x = (1, 2, 3); 3
delete Deletes a property from an object delete obj.key; true
in Checks if a property exists in an object 'key' in obj true
void Evaluates an expression but returns undefined void 0 undefined
Conditional Statements
Control structures that execute specific code blocks based on whether a condition evaluates to true or false.
1. Conditional Statements
Conditional statements are used to perform different actions based on different conditions.
Statement Description Syntax Example
if
Executes a block of code if a specified condition is true.
Syntax
if (condition)
{ code }
Example
if (x > 0)
{ console.log("Positive"); }
if-else
Executes one block of code if the condition is true, otherwise executes another block of code.
Syntax
if (condition) { code1 } else { code2 }
Example
if (x > 0)
{ console.log("Positive"); }
else
{ console.log("Negative"); }
if-else if-else
Tests multiple conditions, executing the block of code for the first true condition.
Syntax
if (condition1)
{ code1 }
else if (condition2)
{ code2 }
else
{ code3 }
Example
if (x > 0) { console.log("Positive"); }
else if (x === 0) { console.log("Zero"); }
else { console.log("Negative"); }
switch
Evaluates an expression, matching its value to multiple case clauses, and executes the matching block.
Syntax
switch(expression)
{ case value1: code;
break;
case value2: code;
Subscribe Infeepedia youtube channel for computer science competitive exams
Download Infeepedia app and call or wapp on 8004391758
Web Tech JavaScript Infeepedia By: Infee Tripathi
break;
default: code; }
Example
switch (day)
{ case 1: console.log("Monday");
break;
case 2: console.log("Tuesday");
break;
default: console.log("Invalid day"); }
Loops
Control structures that repeatedly execute a block of code as long as a specified condition remains true.
Loop Description Syntax Example
for Loops through a block of code a for (initialization; condition; for (let i = 0; i < 5; i++)
specified number of times. increment/decrement) { code } { console.log(i); }
while Loops through a block of code while (condition) { code } let i = 0;
while a specified condition is while (i < 5)
true. { console.log(i);
i++; }
do-while Executes the block of code do { code } while (condition); let i = 0;
once, and then repeats the loop do {
while the condition is true. console.log(i);
i++; }
while (i < 5);
for...in Loops through the properties of for (key in object) { code } let obj = { a: 1, b: 2 };
an object. for (let key in obj)
{ console.log(key, obj[key]);
}
for...of Loops through the values of an for (value of iterable) { code } let arr = [1, 2, 3];
iterable object (like an array or for (let value of arr)
string). { console.log(value); }
Functions in JavaScript
Functions are reusable blocks of code designed to perform a specific task. They help in modularizing and organizing code
efficiently.
1. Function Declaration and Invocation
A function declaration defines a named function with the function keyword. It can be invoked (called) anywhere in the
code after its definition.
Function declarations are hoisted, meaning they can be called before their definition in the code.
A function can take zero or more parameters and return a value.
Syntax
function functionName(parameters) {
// code to execute }
Example
function greet(name)
{
return ‘Hello, ${name}!’; }
// Function Invocation
console.log(greet("Alice")); // Output: Hello, Alice!
console.log(greet("Bob")); // Output: Hello, Bob!
Syntax
const functionName = function(parameters) {
// code to execute };
Example1
// Anonymous function expression
const add = function(a, b) {
return a + b;
};
console.log(add(5, 3)); // Output: 8
Example2
// Named function expression
const multiply = function multiplyNumbers(a, b) {
return a * b;
};
console.log(multiply(4, 2)); // Output: 8
3. Arrow Functions
Arrow functions are a concise way to write functions using the => (arrow) syntax. They are especially useful for writing
shorter functions.
Arrow functions do not have their own this context; they inherit this from the surrounding scope.
For single-line functions, the return keyword can be omitted.
Syntax
const functionName = (parameters) => {
// code to execute };
Example
// Single-line arrow function
const square = (x) => x * x;
console.log(square(4)); // Output: 16
Return Values
The return statement specifies the value to be returned by the function.
If no return is specified, the function returns undefined.
Example2
function multiply(a, b) {
return a * b; }
let result = multiply(3, 4);
console.log(result); // Output: 12
getElementsByClassName()
Selects elements by class name.
document.getElementsByClassName("text")[0]
First element with class="text".
Example:
<p class="text">Paragraph 1</p>
<p class="text">Paragraph 2</p>
<script>
let elements = document.getElementsByClassName("text");
console.log(elements[0].textContent); // Output: Paragraph 1
</script>
getElementsByTagName()
Selects elements by tag name.
document.getElementsByTagName("p")[0]
First <p> element.
Example:
<div>Div 1</div>
<div>Div 2</div>
<script> let elements = document.getElementsByTagName("div");
console.log(elements[1].textContent); // Output: Div 2 </script>
querySelector()
Selects the first matching CSS selector.
document.querySelector(".text")
First element with class="text".
Example:
<p class="text">Paragraph 1</p>
<p class="text">Paragraph 2</p>
<script>
let element = document.querySelector(".text");
console.log(element.textContent); // Output: Paragraph 1
</script>
document.forms
Accesses all <form> elements in the document.
document.forms["loginForm"]
Form with id="loginForm".
Example:
<form id="loginForm"></form>
<script>
let form = document.forms["loginForm"];
console.log(form.id); // Output: loginForm
</script>
document.images
Accesses all <img> elements.
document.images[0]
First <img> element.
Example:
<img src="image.jpg" alt="Example">
<script> let images = document.images;
console.log(images[0].alt); // Output: Example </script>
document.links
Accesses all <a> with href attributes.
document.links[0]
First <a> element with href.
Example:
<a href="https://example.com">Example Link</a>
<script>
let links = document.links;
console.log(links[0].href); // Output: https://example.com/
</script>
Example:
<div id="content">Original Content</div>
<script>
let element = document.getElementById("content");
element.innerHTML = "<strong>Updated Content</strong>";
console.log(element.innerHTML); // Output: <strong>Updated Content</strong>
</script>
textContent
Sets/retrieves plain text content inside an element.
Ignores any HTML tags and treats them as plain text.
element.textContent = "Hi"; //Output: Hi
Example:
<div id="content">Original <strong>Content</strong></div>
<script>
let element = document.getElementById("content");
element.textContent = "Updated Content";
console.log(element.textContent); // Output: Updated Content
</script>
setAttribute()
Sets an attribute value on an element.
element.setAttribute("src", "new.jpg"); //Output: Attribute updated.
Example:
<img id="image" src="old.jpg" alt="Old Image">
<script>
let img = document.getElementById("image");
img.setAttribute("src", "new.jpg");
console.log(img.src); // Output: URL of new.jpg
</script>
getAttribute()
Retrieves the value of a specified attribute on an element..
element.getAttribute("alt"); //Output: Returns attribute value.
Example:
<img id="image" src="example.jpg" alt="Example Image">
<script>
let img = document.getElementById("image");
console.log(img.getAttribute("alt")); // Output: Example Image </script>
removeAttribute()
Removes an attribute from an element.
element.removeAttribute("alt"); //Output: Attribute removed.
Example:
<img id="image" src="example.jpg" alt="Example Image">
<script>
let img = document.getElementById("image");
img.removeAttribute("alt");
console.log(img.hasAttribute("alt")); // Output: false
</script>
style
Modifies inline CSS styles of an element.
element.style.color = "red"; //Output: Style applied.
Example:
<p id="text">Hello, World!</p>
<script>
let text = document.getElementById("text");
text.style.color = "blue";
text.style.fontSize = "20px";
console.log(text.style.color); // Output: blue
</script>
classList
Manages classes of an element. Provides methods to add, remove, toggle, or check classes on an element.
element.classList.add("active");
Class added/removed/toggled.
Example:
<div id="box" class="red"></div>
<script>
let box = document.getElementById("box");
box.classList.add("blue");
box.classList.remove("red");
box.classList.toggle("green");
console.log(box.classList); // Output: DOMTokenList ["blue", "green"]
</script>
appendChild()
Adds a new child element.
parent.appendChild(child);
Child added to parent.
removeChild()
Removes a child element.
parent.removeChild(child);
Child removed.
replaceChild()
Replaces a child element with a new one.
parent.replaceChild(newChild, oldChild);
Child replaced.
Subscribe Infeepedia youtube channel for computer science competitive exams
Download Infeepedia app and call or wapp on 8004391758
Web Tech JavaScript Infeepedia By: Infee Tripathi
Events and Event Handling in JavaScript
Events in JavaScript are actions or occurrences that happen in the browser, such as user interactions (clicking, typing,
scrolling), loading resources, or other activities.
Event Handling refers to the process of responding to these events by executing code.
mouseup:
Triggered when the mouse button is released.
div.addEventListener("mouseup", () => console.log("Mouse button released!"));
Touch Events Triggered by touch touchstart: riggered when a touch starts on a touch-enabled device.
interactions on document.addEventListener("touchstart", () => console.log("Touch started!"));
touch-enabled
devices. touchmove: Triggered when a touch moves across the screen.
document.addEventListener("touchmove", () => console.log("Touch moved!"));
Media Events Triggered by media play: Triggered when media playback starts.
(audio/video) video.addEventListener("play", () => console.log("Playing!"));
playback.
Parameter Description
event The name of the event to listen for (e.g., "click", "mouseover").
callbackFunction The function to execute when the event occurs.
useCapture Optional boolean indicating the phase to handle the event (true for capture, false for bubble).
Event Delegation
Event delegation is a technique where you attach a single event listener to a parent element to handle events on its child
elements. This is useful for managing events dynamically or efficiently when there are many child elements.
Event Delegation is used to:
Reduces the number of event listeners in your code.
Efficient for dynamically created elements.
Simplifies event handling for similar child elements.
Syntax
parentElement.addEventListener(event, (e) => {
if (e.target.matches(selector)) {
callbackFunction(e);
}
});
Parameter Description
parentElement The parent element where the event listener is attached.
event The name of the event to listen for (e.g., "click", "change").
e.target The element that triggered the event.
selector A CSS selector to match the child elements for which the event should be handled.
Creating Arrays
1. Using Array Literals
Syntax: let arrayName = [value1, value2, ...];
Example:
let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits); // Output: ["Apple", "Banana", "Cherry"]
Manipulating Arrays
Example:
let fruits = ["Apple", "Banana"];
fruits.push("Cherry");
console.log(fruits); // Output: ["Apple", "Banana", "Cherry"]
pop()
Removes the last element from an array.
Returns the removed element.
Syntax :
array.pop();
Example:
let fruits = ["Apple", "Banana", "Cherry"];
let lastFruit = fruits.pop();
console.log(fruits); // Output: ["Apple", "Banana"]
console.log(lastFruit); // Output: "Cherry"
Example:
let fruits = ["Banana", "Cherry"];
fruits.unshift("Apple");
console.log(fruits); // Output: ["Apple", "Banana", "Cherry"]
map()
Creates a new array by applying a function to each element of the original array.
Syntax:
array.map(callback);
Example:
let numbers = [1, 2, 3];
let squared = numbers.map(num => num * num);
console.log(squared); // Output: [1, 4, 9]
filter()
Creates a new array with elements that pass a test implemented by a function.
Syntax:
array.filter(callback);
Example:
let numbers = [1, 2, 3, 4, 5];
let evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]
find()
Returns the first element in the array that satisfies a given condition.
If no element satisfies the condition, it returns undefined.
Syntax:
array.find(callback(element, index, array));
Example:
let numbers = [1, 3, 5, 7, 8];
let firstEven = numbers.find(num => num % 2 === 0);
console.log(firstEven); // Output: 8
findIndex()
Returns the index of the first element that satisfies a given condition.
If no element satisfies the condition, it returns -1.
Syntax:
array.findIndex(callback(element, index, array));
Example:
let numbers = [1, 3, 5, 7, 8];
let firstEvenIndex = numbers.findIndex(num => num % 2 === 0);
console.log(firstEvenIndex); // Output: 4
every()
Tests whether all elements in the array satisfy a given condition.
Returns true if all elements pass the test; otherwise, false.
Syntax:
array.every(callback(element, index, array));
Example:
let numbers = [2, 4, 6, 8];
let allEven = numbers.every(num => num % 2 === 0);
console.log(allEven); // Output: true
some()
Tests whether at least one element in the array satisfies a given condition.
Returns true if any element passes the test; otherwise, false.
Syntax:
array.some(callback(element, index, array));
Example:
let numbers = [1, 3, 5, 7, 8];
let hasEven = numbers.some(num => num % 2 === 0);
console.log(hasEven); // Output: true
Example:
let numbers = [10, 3, 7, 1];
numbers.sort((a, b) => a - b); // Ascending order
console.log(numbers); // Output: [1, 3, 7, 10]
reverse()
Reverses the order of elements in an array in place.
Syntax:
array.reverse();
Example:
let numbers = [1, 2, 3, 4];
numbers.reverse();
console.log(numbers); // Output: [4, 3, 2, 1]
Objects in JavaScript
Objects in JavaScript are collections of properties and methods. They represent real-world entities and are a cornerstone of
JavaScript programming.
1. Properties
Properties are key-value pairs associated with an object.
The key is always a string (or symbol), and the value can be any data type (string, number, object, function, etc.).
Syntax:
let objectName = {
property1: value1,
property2: value2,
};
Example:
let car = {
brand: "Toyota",
model: "Corolla",
year: 2022,
};
console.log(car.brand); // Output: Toyota
2. Methods
Methods are functions defined as properties of an object.
They allow objects to perform actions.
Syntax:
let objectName = {
methodName: function() {
// Code here
}, };
Object Creation
Using new Object(): Creates an empty object and adds let user = new Object();
properties later. user.name = "John";
user.age = 30;
Using Constructor Functions Used to create multiple objects of the function User(name, age) {
same type. this.name = name;
this.age = age;
}
let user1 = new User("Alice", 25);
let user2 = new User("Bob", 30);
Callbacks
A callback is a function passed as an argument to another function, executed after the completion of an asynchronous
operation.
Example: Imagine ordering pizza. You give your phone number to the pizza shop (callback). When the pizza is ready, they call
you to notify you (execute the callback).
Syntax
function asyncOperation(callback) {
setTimeout(() => {
console.log("Operation Complete"); callback(); }, 1000);
}
Output:
Start
End
Operation Complete
Callback executed!
Advantages
Simple to use for basic tasks.
Disadvantages
Can lead to "callback hell."
Note: Callback Hell: Callback hell happens when you use too many nested callbacks, making your code hard to read, debug,
and maintain. It looks like a "pyramid" or "ladder" because one function depends on the result of the previous function.
Promises
A Promise is an object that represents a task that will complete in the future (success or failure). It has three states:
States of a Promise
State Description
Pending Initial state, neither fulfilled nor rejected.
Fulfilled Operation completed successfully.
Rejected Operation failed.
Syntax
const promise = new Promise((resolve, reject) => {
if (condition) {
resolve("Success");
} else {
reject("Error");
}
});
Example
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data fetched successfully!");
}, 1000);
});
};
fetchData()
.then((data) => console.log(data))
.catch((error) => console.error(error));
Output:
Data fetched successfully!
Subscribe Infeepedia youtube channel for computer science competitive exams
Download Infeepedia app and call or wapp on 8004391758
Web Tech JavaScript Infeepedia By: Infee Tripathi
Advantages
Avoids callback hell.
Chainable .then() and .catch().
Disadvantages
Requires more code for simple operations.
Still requires careful error handling.
Async/Await
Async/await is a syntactic sugar over promises, making asynchronous code look and behave more like synchronous code.
Example: Instead of constantly checking for your package (callbacks or .then), you simply wait until it's delivered (await).
Syntax
async function asyncFunction() {
try {
const result = await promise;
console.log(result);
} catch (error) {
console.error(error);
}
}
Example
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data fetched successfully!");
}, 1000);
});
};
async function fetchAndDisplay() {
console.log("Fetching data...");
const data = await fetchData();
console.log(data);
}
fetchAndDisplay();
Output:
Fetching data...
Data fetched successfully!
Advantages
Simplifies asynchronous code.
Better error handling with try-catch.
Disadvantages
Requires modern JavaScript environments.
May block execution within await.
Feature Description
Promise-Based The Fetch API uses promises, making it easier to handle asynchronous requests.
Default Method The default HTTP method is GET, but you can specify others like POST, PUT, and DELETE.
Response Object The response object provides methods like .json(), .text(), and .blob() to parse responses.
Supports Headers You can set custom headers for requests.
Syntax
fetch(url, options)
.then(response => {
// Handle the response
})
.catch(error => {
// Handle errors
});
Parameter Description
url The URL to which the request is sent.
options Optional object specifying request details like method, headers, body, etc.
Handling Responses
The response object provides methods to process the data:
Method Description Example
.json() Parses the response as JSON. response.json()
.text() Parses the response as plain text. response.text()
.blob() Parses the response as a binary large object (e.g., images). response.blob()
.status Returns the HTTP status code of the response. response.status
.ok Returns true if the HTTP status code is in the range 200–299. response.ok
5. Network Tab: The Network tab helps debug HTTP requests and responses.
Feature Description
Status Code Shows HTTP status codes like 200, 404, etc.
Headers Displays request and response headers.
Payload Shows the data sent in requests.
6. Debugger Keyword : The debugger keyword pauses code execution at a specific point.