0% found this document useful (0 votes)
22 views69 pages

Javascript

JavaScript is a lightweight, interpreted programming language essential for web interactivity and development, widely used for both front-end and back-end applications. It is highly popular, versatile, and supported by a large community, with numerous frameworks and libraries available. While it offers many advantages like enhanced user experience and reduced server load, it also has limitations such as security risks and browser compatibility issues.

Uploaded by

tekaleadesh67
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views69 pages

Javascript

JavaScript is a lightweight, interpreted programming language essential for web interactivity and development, widely used for both front-end and back-end applications. It is highly popular, versatile, and supported by a large community, with numerous frameworks and libraries available. While it offers many advantages like enhanced user experience and reduced server load, it also has limitations such as security risks and browser compatibility issues.

Uploaded by

tekaleadesh67
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JavaScript

 What is JavaScript?

i. JavaScript is a lightweight, interpreted programming language.


ii. It is primarily known for adding interactivity to web pages.
iii. As one of the core technologies of the World Wide Web alongside HTML and CSS,
JavaScript enables dynamic content, control of multimedia, animation, and much more.

 Why JavaScript?
1. Popularity:

 JavaScript is the most popular programming language globally.

2. Versatility:

 It is used for both front-end and back-end development with frameworks like jQuery and
[Link].

3. Accessibility:

 JavaScript is pre-installed on all modern web browsers (Chrome, Firefox, Safari, etc.).
 No special setup is required to start learning.

4. Web Development:

 Enables the creation of fast and visually appealing websites.


 Enhances user experience with dynamic and interactive features.

5. Expanded Usage:

 Used in mobile app development, desktop app development, and game development.
 Offers numerous opportunities for JavaScript programmers.

6. Job Market:

 High demand for JavaScript skills leads to many job opportunities and good pay.
 Job sites reflect the strong demand for JavaScript developers.

7. Frameworks and Libraries:

 Numerous frameworks and libraries available to speed up development.


 Over 150,000 JavaScript libraries exist, and the number is growing.

8. Industry Adoption:

 Used by major companies like Google, Meta, Microsoft, PayPal, and LinkedIn.

9. Community Support:
 Large online community of learners, developers, and mentors.
 Easy to find support and resources online.

 Client-Side JavaScript
Client-side JavaScript refers to JavaScript code that runs in the user's web browser. It allows for creating
interactive and dynamic web pages. Here are some examples of client-side JavaScript functionalities:

 Form validation before submitting to the server.


 Interactive maps.
 Animations and effects.
 Content updates without reloading the page (AJAX).

 Advantages of JavaScript
1. Interactivity: Enhances the user experience by enabling interactive web pages.
2. Reduced Server Load: Can validate and process data on the client side, reducing the need for server
interaction.
3. Speed: Runs immediately within the client's browser without needing server interaction.
4. Versatility: Compatible with various browsers and platforms.

 Limitations of JavaScript
1. Security Risks: Can be exploited for malicious purposes, such as cross-site scripting (XSS).
2. Browser Compatibility: Different browsers may interpret JavaScript differently, though this is less
of an issue with modern browsers.
3. Client-Side Dependency: Relies on the client's processing power and can be disabled by the user.

 Application of JavaScrip
Client-side Validation:

 Verifies user input before submitting to the server.


 JavaScript validates inputs on the front-end.

Manipulating HTML Pages:

 JavaScript can dynamically manipulate HTML pages.


 Easily add or delete HTML tags.
 Modify HTML to adjust appearance based on devices and requirements.

User Notifications:

 JavaScript can create dynamic pop-ups for user notifications on web pages.

Back-end Data Loading:


 The Ajax library in JavaScript allows loading back-end data during other processes.
 Enhances user experience by providing seamless data updates.

Presentations:

 JavaScript can create web-based slide presentations.


 Libraries like RevealJS and BespokeJS are used for this purpose.

Server Applications:

 [Link], built on Chrome's JavaScript runtime, is used for developing fast, scalable network
applications.
 [Link] is event-based, making it suitable for sophisticated server applications, including web
servers.

Machine Learning:

 The [Link] library allows developers to perform machine learning tasks.

Game Development:

 JavaScript includes multiple libraries and NPM packages for designing game graphics.
 Combined with HTML and CSS, JavaScript can be used to develop games.

Mobile Applications:

 Frameworks like React Native enable the development of feature-rich mobile applications.

Internet of Things (IoT):

 JavaScript adds functionality to IoT devices like smartwatches and earbuds.

Data Visualization:

 Libraries like [Link] are used for efficient data visualization.


 [Link] helps create high-quality charts and visual data representations.

Cloud Computing:

 JavaScript is used in serverless computing platforms like Cloudflare and AWS Lambda.
 Enables writing and deploying functions on the cloud.

 JavaScript Development Tools


1. Web Browsers: Built-in developer tools (e.g., Chrome DevTools, Firefox Developer Tools).
2. Text Editors and IDEs: Tools like Visual Studio Code, Sublime Text, and WebStorm.
3. Version Control Systems: Git for version control and collaboration.
4. Build Tools: Tools like Webpack, Babel for module bundling and transpiling.
 Where is JavaScript Today?
JavaScript is ubiquitous in web development and has also expanded into server-side development
([Link]), mobile app development (React Native), desktop applications (Electron), and even
machine learning and AI ([Link]).

 JavaScript – Syntax

Your First JavaScript Code

Here is a simple example of JavaScript code embedded in an HTML file:

<!DOCTYPE html>
<html>
<head>
<title>My First JavaScript</title>
</head>
<body>
<h1>Hello, World!</h1>
<script>
[Link]('Hello, World!');
</script>
</body>
</html>

1. Whitespace and Line Breaks

JavaScript ignores extra whitespace and line breaks, making it flexible for formatting:

let x = 5;
let y = 6;
let z = x + y;

This code is equivalent to:

let x=5;let y=6;let z=x+y;

2. Semicolons are Optional

Semicolons are used to terminate statements but are often optional due to automatic
semicolon insertion (ASI). However, it's good practice to use them to avoid potential errors:

let x = 5;
let y = 6;
let z = x + y;

3. Case Sensitivity

JavaScript is case-sensitive, meaning that myVariable and myvariable are considered


different identifiers.
4. Comments in JavaScript

SComments are used to explain code and are ignored by the interpreter.

 Single-line comments: Use // for single line comment.

// This is a single-line comment


let x = 5; // Comment after a statement

 Multi-line comments: Use /* */ for multi-line comment

/* This is a
multi-line comment */
let y = 10;

 JavaScript – Enabling

A. JavaScript in Internet Explorer

To enable JavaScript in Internet Explorer:


1. Open the Tools menu and select "Internet Options."
2. Go to the "Security" tab.
3. Click "Custom Level" and scroll down to the "Scripting" section.
4. Enable "Active Scripting."

B. JavaScript in Firefox

To enable JavaScript in Firefox:


A. Open the menu and select "Options."
B. Go to the "Privacy & Security" panel.
C. Scroll down to the "Permissions" section.
D. Ensure that the "Enable JavaScript" option is checked.

C. JavaScript in Chrome

To enable JavaScript in Chrome:

i. Open the Chrome menu and select "Settings."


ii. Scroll down and click "Advanced."
iii. In the "Privacy and security" section, click "Content settings."
iv. Click "JavaScript" and toggle the switch to "Allowed."

D. JavaScript in Opera

To enable JavaScript in Opera:

1. Open the Opera menu and select "Settings."


2. Click "Advanced" in the sidebar.
3. In the "Privacy and security" section, click "Content settings."
4. Click "JavaScript" and toggle the switch to "Allowed."

 Warning for Non-JavaScript Browsers:-


For browsers that do not support JavaScript or have it disabled, you can provide a warning message
using the <noscript> tag:
e.g.
<noscript>
<p>Your browser does not support JavaScript, or it is disabled. Some features may not be
available.</p>
</noscript>

 JavaScript – Placement

A. JavaScript in <head>...</head> Section


i. JavaScript code can be placed within the <head> section of an HTML document.
ii. This is useful for scripts that need to run before the page content is loaded:

Example

<!DOCTYPE html>
<html>
<head>
<script>
[Link]("This script is in the head section.");
</script>
</head>
<body>
<h1>JavaScript in Head</h1>
</body>
</html>

B. JavaScript in <body>...</body> Section


i. Placing JavaScript code at the end of the <body> ensures that the HTML content is
loaded before the script runs:

Example

<!DOCTYPE html>
<html>
<head>
<title>JavaScript in Body</title>
</head>
<body>
<h1>JavaScript in Body</h1>
<script>
[Link]("This script is in the body section.");
</script>
</body>
</html>

C. JavaScript in <body> and <head> Sections


i. JavaScript can be placed in both the <head> and <body> sections, but this is less
common and can complicate the script execution order.
D. JavaScript in External File
i. Placing JavaScript in an external file is a best practice for maintainability and reusability.
ii. Create a .js file and reference it in the HTML:

Example

<!DOCTYPE html>
<html>
<head>
<title>External JavaScript</title>
<script src="[Link]"></script>
</head>
<body>
<h1>External JavaScript</h1>
</body>
</html>

Contents of [Link]:

[Link]("This script is in an external file.");

 Javascript – output

1. [Link]()

 Description: This method writes HTML expressions or JavaScript code to a document.


 Usage:

[Link]('Hello, World!');

 Output: Directly writes the specified content to the document where the script is located.
Useful for quick testing or simple output directly in the HTML document.

2. innerHTML

 Description: Property that sets or returns the HTML content (inner HTML) of an element.
 Usage:

let element = [Link]('myElement');


[Link] = 'Hello, World!';

 Output: Sets the HTML content of the specified element. This method is commonly used to
dynamically update or change the content of an HTML element based on JavaScript logic or
user input.

3. [Link]()

 Description: Outputs a message to the browser's console (or terminal in [Link]).


 Usage:

[Link]('Hello, World!');
 Output: Prints the specified message to the browser's console. Useful for debugging
JavaScript code, as it allows developers to inspect variables, objects, and see the flow of
execution without altering the document itself.

 JavaScript – Variables
i. In JavaScript, variables can be declared using var, let, and const.
ii. Variables in JavaScript are containers for storing data values:

1. var

 Function-scoped: Variables declared with var are scoped to the function in which they are declared
or globally if they are declared outside any function.
 Hoisting: var variables are hoisted to the top of their scope, meaning you can reference them before
their declaration, though they will be undefined until the declaration is encountered.

E.g.

[Link](x); // undefined
var x = 5;
[Link](x); // 5

2. let
 Block-scoped: Variables declared with let are scoped to the block in which they are declared (i.e.,
enclosed by curly braces {}).
 No hoisting (in the same way as var): let variables are not accessible before their declaration,
leading to a "temporal dead zone".

E.g.

{
let y = 10;
[Link](y); // 10
}
[Link](y); // ReferenceError: y is not defined

3. const

 Block-scoped: Similar to let, const is also block-scoped.


 Constant value: const variables must be initialized at the time of declaration and cannot be
reassigned.

E.g.

const z = 15;
[Link](z); // 15
z = 20; // TypeError: Assignment to constant variable.

Examle of variables in javascript

let x = 5; // Declaring a variable 'x' with value 5


let message = "Hello, JavaScript!"; // Declaring a variable 'message' with a string value
const PI = 3.14; // Declaring a constant variable 'PI'

 Variable Scope
Scope determines the accessibility of variables. JavaScript has two types of scope:

 Global Scope: Variables declared outside any function or block are in the global scope and
can be accessed from anywhere in the code.
 Local Scope: Variables declared inside a function or block are in local scope and can only be
accessed within that function or block.
 Function Scope: Variables declared with var inside a function are only accessible within that
function.

E.g of functional scope

function myFunction() {
var a = 10;
[Link](a); // 10
}
[Link](a); // ReferenceError: a is not defined

 Block Scope: Variables declared with let or const inside a block are only accessible within
that block.

 E.g of Block scope

if (true) {
let b = 20;
[Link](b); // 20
}
[Link](b); // ReferenceError: b is not defined

Variables in JavaScript have function-level scope:

function scopeExample() {
if (true) {
var localVar = "I'm a local variable";
}
[Link](localVar); // localVar is accessible here
}
scopeExample();
[Link](localVar); // Error: localVar is not defined outside the function

o JavaScript Variable Names

Rules for variable names in JavaScript:


 Must begin with a letter, $, or _.
 Subsequent characters can include letters, numbers, $, or _.
 Case-sensitive (myVariable is different from MyVariable).

o JavaScript Reserved Words

Reserved words are predefined by JavaScript and cannot be used as variable names:

let let = 5; // Error: 'let' is a reserved word


let break = "break"; // Error: 'break' is a reserved word

 JavaScript Datatypes
JavaScript supports several datatypes:

 Primitive Datatypes: number, string, boolean, undefined, null, symbol.


 Complex Datatypes: object, function, array.

Data
Category Description Example
Type
A variable that has been declared
Undefined Primitive let x;
but not assigned
Intentional absence of any object
Null Primitive let y = null;
value
Logical entity with values true or
Boolean Primitive let isTrue = true;
false
Integer and floating-point
Number Primitive let num = 42;
numbers
let bigInt =
BigInt Primitive Integers with arbitrary precision
1234567890123456789012345678901234567890n;
String Primitive Sequence of characters let str = "Hello, world!";
Symbol Primitive Unique identifier let sym = Symbol('description');
Object Object Collection of key-value pairs let obj = {name: "John", age: 30};
Array Object Ordered list of values let arr = [1, 2, 3];
Block of code designed to
Function Object let func = function() { return "Hello!"; };
perform a task
Date Object Represents dates and times let date = new Date();
RegExp Object Represents regular expressions let regex = /ab+c/;

 JavaScript – Operators
What is an Operator?

Operators in JavaScript are symbols that perform operations on operands (variables or values).

1. Arithmetic Operators
Arithmetic operators are used to perform mathematical calculations.

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
++ Increment let a = 5; a++ 6 (after increment)
-- Decrement let b = 5; b-- 4 (after decrement)

Example:

let x = 5;
let y = 2;
[Link](x + y); // Addition: 7
[Link](x - y); // Subtraction: 3
[Link](x * y); // Multiplication: 10
[Link](x / y); // Division: 2.5
[Link](x % y); // Modulus: 1
[Link](++x); // Increment: 6
[Link](--y); // Decrement: 1

2. Comparison Operators
Comparison operators are used to compare two values and return a boolean value.

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

Example:

let a = 5;
let b = 10;
[Link](a == b); // Equal to: false
[Link](a != b); // Not equal to: true
[Link](a > b); // Greater than: false
[Link](a < b); // Less than: true
[Link](a >= b); // Greater than or equal to: false
[Link](a <= b); // Less than or equal to: true

3. Logical Operators
Logical operators are used to combine multiple boolean expressions.
Operator Description Example Result
&& Logical AND true && false false
|| Logical OR true || false true
! Logical NOT !true false

Example:

let p = true;
let q = false;
[Link](p && q); // Logical AND: false
[Link](p || q); // Logical OR: true
[Link](!p); // Logical NOT: false

4. Bitwise Operators
Bitwise operators work on the binary representations of numbers.

Operator Description Example Result


& AND 5&1 1
| OR 5|3 7
^ XOR 5^1 4
~ NOT ~5 -6
<< Left shift 5 << 1 10
>> Right shift 5 >> 1 2
>>> Zero-fill right shift 5 >>> 1 2

Example:

let m = 5; // 101 in binary


let n = 3; // 011 in binary
[Link](m & n); // Bitwise AND: 1 (001)
[Link](m | n); // Bitwise OR: 7 (111)
[Link](m ^ n); // Bitwise XOR: 6 (110)
[Link](~m); // Bitwise NOT: -6 (111...1010)
[Link](m << 1); // Bitwise left shift: 10 (1010)
[Link](m >> 1); // Bitwise right shift: 2 (10)

5. Assignment Operators
Assignment operators assign values to variables.

Operator Description Example Result


= Assign x = 10 x is 10
+= Add and assign x += 5 x=x+5
-= Subtract and assign x -= 5 x=x-5
*= Multiply and assign x *= 5 x=x*5
/= Divide and assign x /= 5 x=x/5
Operator Description Example Result
%= Modulus and assign x %= 5 x=x%5
**= Exponentiation and assign x **= 2 x = x ** 2

Example:

let x = 5;
x += 2; // Equivalent to x = x + 2 (x is now 7)
x -= 2; // Equivalent to x = x - 2 (x is now 5 again)
x *= 2; // Equivalent to x = x * 2 (x is now 10)
x /= 2; // Equivalent to x = x / 2 (x is now 5 again)

6. Miscellaneous Operators

Operator Description Example Result


, Comma let a = (1, 2, 3); 3 (returns the last value)
delete
delete Deletes a property from an object true if successful
[Link]
Checks if a property is in an
in 'prop' in obj true if obj has prop
object
new Creates an instance of an object new Object() Creates a new object
The value of the current object’s
this Refers to the current object [Link]
property

Example:
let str1 = "Hello";
let str2 = " JavaScript!";
[Link](str1 + str2); // Concatenation: "Hello JavaScript!"
[Link](5 ** 2); // Exponentiation: 25 (5 raised to the power of 2)
[Link](typeof x); // Typeof operator: "number"
[Link](delete x); // Delete operator: true (if successful)

7. Conditional (Ternary) Operator


The conditional (ternary) operator is the only JavaScript operator that takes three operands.

Operator Description Example Result


?: Conditional condition ? val1 : val2 If condition is true, the result is val1; otherwise, val2

Example
let age = 18;
let canVote = (age >= 18) ? 'Yes' : 'No';
[Link](canVote); // 'Yes'

8. Type Operators
Type operators are used to get the type of a variable or convert types.
Operator Description Example Result
typeof Returns the type of a variable typeof 5 "number"
Checks if an object is an instance of a obj instanceof true if obj is an instance of
instanceof
constructor Array Array
Evaluates an expression and returns
void void(0) undefined
undefined

Example

let x = 5;
[Link](typeof x); // 'number'

let arr = [1, 2, 3];


[Link](arr instanceof Array); // true

9. String Operators

String operators are used to manipulate string values.

Operator Description Example Result


+ Concatenation 'Hello' + ' World!' 'Hello World!'
+= Concatenation and assign let str = 'Hello'; str += ' World!' 'Hello World!'

Example
let str1 = 'Hello';
let str2 = 'World';
[Link](str1 + ' ' + str2); // 'Hello World'

 JavaScript – If-Else

Flow Chart of If-Else

Here's a simplified flow chart to visualize the if-else decision-making process:

1. Evaluate the condition.


2. If the condition is true, execute the "if" block.
3. If the condition is false, execute the "else" block (if present).

A. if Statement

The if statement is used to execute a block of code if a specified condition is true.

Syntax:

if (condition)

{
// code to be executed if the condition is true
}

Example:
let hour = 15;
if (hour < 18) {
[Link]("Good day!"); // Outputs: Good day!
}

B. if...else Statement

The if...else statement executes one block of code if a condition is true, and another block if the
condition is false.

Syntax:

if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}

Example:

let hour = 21;


if (hour < 18) {
[Link]("Good day!");
} else {
[Link]("Good evening!"); // Outputs: Good evening!
}

C. if...else if...else Statement

The if...else if...else statement is used to specify a new condition if the first condition is false.

Syntax:

if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if both condition1 and condition2 are false
}

Example:

let hour = 10;


if (hour < 12) {
[Link]("Good morning!"); // Outputs: Good morning!
} else if (hour < 18) {
[Link]("Good day!");
} else {
[Link]("Good evening!");
}

 JavaScript – Switch-Case

Flow Chart
A switch-case statement is used for selecting one of many code blocks to be executed. The flow is as
follows:

1. Evaluate the expression.


2. Match the expression’s value with a case.
3. Execute the corresponding case block.
4. Use break to exit the switch block.

Syntax:

switch (expression) {
case value1:
// code to be executed if expression === value1
break;
case value2:
// code to be executed if expression === value2
break;
// add more cases as needed
default:
// code to be executed if no case matches
}

Example:

let day = 3;
switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday"); // Outputs: Wednesday
break;
default:
[Link]("Another day");
}

 JavaScript – While Loop

1. The while Loop

The while loop executes a block of code as long as the specified condition is true.

Syntax:

while (condition) {
// code block to be executed
}

Example:

let i = 0;
while (i < 5) {
[Link](i); // Outputs: 0, 1, 2, 3, 4
i++;
}

2. The do...while Loop

The do...while loop is similar to the while loop, but it ensures that the block of code is executed at
least once.

Syntax:

do {
// code block to be executed
} while (condition);

Example:

let i = 0;
do {
[Link](i); // Outputs: 0, 1, 2, 3, 4
i++;
} while (i < 5);

 JavaScript – For Loop

1. The for Loop

The for loop is used when you know beforehand how many times you want to execute a statement or
a block of statements.

Syntax:

for (initialization; condition; increment) {


// code block to be executed
}

Example:

for (let i = 0; i < 5; i++) {


[Link](i); // Outputs: 0, 1, 2, 3, 4
}

 JavaScript – For-in Loop

1. The for-in Loop

The for-in loop iterates over the enumerable properties of an object.

Syntax:

for (variable in object) {

// code block to be executed


}
Example:

let person = {
name: 'John',
age: 30,
city: 'New York'
};

for (let key in person) {


[Link](key + ': ' + person[key]); // Outputs: name: John, age: 30, city: New York
}

 JavaScript – Loop Control

1. The break Statement

The break statement exits the loop immediately, regardless of the loop’s condition.

Example:

for (let i = 0; i < 10; i++) {


if (i === 5) {
break; // Exit the loop when i equals 5
}
[Link](i); // Outputs: 0, 1, 2, 3, 4
}

2. The continue Statement

The continue statement skips the current iteration and proceeds to the next iteration of the loop.

Example:

for (let i = 0; i < 10; i++) {


if (i === 5) {
continue; // Skip the iteration when i equals 5
}
[Link](i); // Outputs: 0, 1, 2, 3, 4, 6, 7, 8, 9
}

3. Using Labels to Control the Flow

Labels can be used to control the flow of nested loops when using break and continue.

Example:

outerLoop: for (let i = 0; i < 3; i++) {


innerLoop: for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) {
break outerLoop; // Exit both loops when i equals 1 and j equals 1
}
[Link](`i = ${i}, j = ${j}`); // Outputs: i = 0, j = 0 ... i = 0, j = 2 ... i = 1, j = 0
}
}
 JavaScript – Functions
i. Functions are a fundamental aspect of JavaScript, allowing you to encapsulate code for
reuse, modularity, and organization.

ii. A JavaScript function is a block of code designed to perform a particular task.

iii. A JavaScript function is executed when "something" invokes it (calls it).

iv. Here's an in-depth look at various aspects of functions in JavaScript:

A. Function Definition
i. A JavaScript function is defined with the function keyword, followed by a name, followed
by parentheses ().
ii. Function names can contain letters, digits, underscores, and dollar signs (same rules as
variables).
iii. The parentheses may include parameter names separated by commas: (parameter1,
parameter2, ...)
iv. The code to be executed by the function is placed inside curly brackets {}.

Syntax:

function name(parameter1, parameter2, parameter3) {

// code to be executed

Example:

function greet(name) {

[Link]('Hello, ' + name + '!');


}

// Function call
greet('Alice'); // Output: Hello, Alice!

 Calling a Function
Functions are called by using their name followed by parentheses containing arguments (if any).

Example:

greet('Bob'); // Output: Hello, Bob!

 Function Parameters
Function parameters are placeholders for values that are passed to the function when it is called.
These parameters are used within the function body.

Example:

function greet(name) {
[Link]('Hello, ' + name + '!');
}
greet('Alice'); // Output: Hello, Alice!

 The return Statement


The return statement specifies the value returned by the function. When the return statement is
executed, the function stops executing and returns the specified value to the caller.

Example:

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

let result = add(3, 5);


[Link](result); // Output: 8

 Nested Functions
Functions can be defined inside other functions. These are called nested functions or inner functions.
The inner function is accessible only within the outer function.

Example:

function outerFunction() {
[Link]('Outer function');

function innerFunction() {
[Link]('Inner function');
}

innerFunction(); // Call inner function


}

outerFunction(); // Output: Outer function, Inner function

 Function() Constructor

Functions can also be created using the Function constructor, which takes the parameter names and
function body as strings.

Syntax:

let myFunction = new Function('param1', 'param2', 'function body');

Example:

let add = new Function('a', 'b', 'return a + b;');


[Link](add(2, 3)); // Output: 5

 Function Literals

Function literals are anonymous functions defined without a name. They are typically assigned to a
variable.
Syntax:

let variableName = function(parameters) {


// code to be executed
};

Example:

let multiply = function(x, y) {


return x * y;
};

[Link](multiply(2, 3)); // Output: 6

 JavaScript – Events
Events are actions or occurrences that happen in the system you are programming, which the system
tells you about so your code can respond to them. Events can be triggered by user actions like
clicking a button, submitting a form, or moving the mouse.

Tabular format describing JavaScript events:

Event Type Description Example Usage


Events triggered by mouse actions such as clicks, onclick, onmouseover,
Mouse Events
movements, and hovering. onmouseout
Events triggered by keyboard actions such as key presses
Keyboard Events onkeydown, onkeyup, onkeypress
and releases.
Events related to form element interactions, like
Form Events onsubmit, onchange, oninput
submitting forms or changing input values.
Events related to the browser window, such as loading,
Window Events onload, onresize, onscroll
resizing, or scrolling the page.
Document Events associated with the document, like when the DOM DOMContentLoaded,
Events is fully loaded or content is ready to be manipulated. onreadystatechange
Events triggered by multimedia elements such as <audio>
Media Events onplay, onpause, onended
and <video> when they play, pause, or end.
Events related to dragging elements, such as when they
Drag Events ondragstart, ondrag, ondragend
are dragged, dropped, or dragged over a target.
Clipboard Events related to clipboard actions like copying and
oncut, oncopy, onpaste
Events pasting content.
Events triggered by touch interactions on touch-enabled ontouchstart, ontouchmove,
Touch Events
devices. ontouchend
Animation Events associated with CSS animations and transitions, animationstart, animationend,
Events like when an animation starts or ends. animationiteration
Miscellaneous Other events not fitting into specific categories, like error
onerror, onfocus, onblur
Events events and focus-related events.

 What is an Event?
An event is an action or occurrence detected by the program that can trigger specific functionality.
Events are central to the way JavaScript interacts with HTML and allows for dynamic and
interactive web pages.

A. onclick Event Type

The onclick event type triggers when an element is clicked. It's one of the most commonly used
events for adding interactivity to web pages.

Example:

<button onclick="alert('Button clicked!')">Click Me</button>

//In this example, an alert box will be displayed when the button is clicked.

B. onsubmit Event Type

The onsubmit event type triggers when a form is submitted. This event is typically used for
validating form data before sending it to the server.

Example:

<form onsubmit="alert('Form submitted!')">


<input type="submit" value="Submit">
</form>

//In this example, an alert box will be displayed when the form is submitted.

C. onmouseover and onmouseout

The onmouseover event triggers when the mouse pointer moves over an element, and the
onmouseout event triggers when the mouse pointer moves out of an element. These events are useful
for creating interactive effects such as tooltips or changing the appearance of elements when
hovered.

Example:

<img src="[Link]" onmouseover="[Link]('Mouse over image')"


onmouseout="[Link]('Mouse out of image')">

//In this example, messages will be logged to the console when the mouse pointer moves over
and out of the image.

 HTML5 Standard Events

HTML5 introduces many standard events like DOMContentLoaded, input, change, etc., which are
widely used for handling specific actions or interactions.

 DOMContentLoaded: Triggers when the initial HTML document has been completely
loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.

Example
[Link]('DOMContentLoaded', (event) => {
[Link]('DOM fully loaded and parsed');
});
 input: Triggers when the value of an <input>, <textarea>, or <select> element has been
changed.

Example
<input type="text" id="myInput" oninput="[Link]('Input changed')">

 change: Triggers when the value of an element has been changed and the element has lost
focus.

Example

<input type="text" id="myInput" onchange="[Link]('Value changed')">

 JavaScript – Event Handler


Event handlers are script wriiten by programmer to handle the [Link] event handlers are
executes when the special event occurs.
Following is a list of event handlers:

A. Selection List (Dropdown, Select)

Event Description Example Usage


Occurs when the value of the select javascript <select onchange="handleChange()">...
onchange
element changes. </select>

B. Text Element (Input, Textarea)

Event Description Example Usage


Occurs when the value of an <input> or
oninput javascript <input oninput="handleInput()">
<textarea> element is changed.
Occurs when the value of an <input> or javascript <input
onchange
<textarea> element is changed and focus is lost.
onchange="handleChange()">
javascript <input
onfocus Occurs when an element gets focus.
onfocus="handleFocus()">
onblur Occurs when an element loses focus. javascript <input onblur="handleBlur()">
javascript <input
onkeydown Occurs when a key is pressed down.
onkeydown="handleKeyDown()">
javascript <input
onkeyup Occurs when a key is released.
onkeyup="handleKeyUp()">
javascript <input
onkeypress Occurs when a key is pressed down and released.
onkeypress="handleKeyPress()">

C. Button
Event Description Example Usage
Occurs when the button is javascript <button onclick="handleClick()">Click
onclick
clicked. me</button>
Occurs when the button is javascript <button ondblclick="handleDblClick()">Double
ondblclick
double-clicked. click me</button>
javascript <button
Occurs when a mouse button is
onmousedown onmousedown="handleMouseDown()">Hold
pressed down on an element.
me</button>
Occurs when a mouse button is javascript <button
onmouseup
released over an element. onmouseup="handleMouseUp()">Release me</button>

D. Document

Event Description Example Usage


Occurs when the document has
onload javascript <body onload="handleLoad()">
finished loading.
Occurs when the document is
onunload javascript <body onunload="handleUnload()">
being unloaded.
Occurs when the document view is javascript [Link] = function() { handleResize();
onresize
resized. };
Occurs when an element's scrollbar javascript [Link] = function() { handleScroll();
onscroll
is being scrolled. };
Occurs when a key is pressed javascript [Link] = function(event) {
onkeydown
down. handleKeyDown(event); };
javascript [Link] = function(event) {
onkeyup Occurs when a key is released.
handleKeyUp(event); };
Occurs when a key is pressed down javascript [Link] = function(event) {
onkeypress
and released. handleKeyPress(event); };

E. Mouse Events

Event Description Example Usage


javascript [Link] = function() {
onclick Occurs when an element is clicked.
handleClick(); };
Occurs when an element is double- javascript [Link] = function() {
ondblclick
clicked. handleDblClick(); };
Occurs when a mouse button is pressed javascript [Link] = function() {
onmousedown
down on an element. handleMouseDown(); };
Occurs when a mouse button is released javascript [Link] = function() {
onmouseup
over an element. handleMouseUp(); };
Occurs when the pointer is moving javascript [Link] = function() {
onmousemove
while it is over an element. handleMouseMove(); };
Occurs when the pointer is moved onto javascript [Link] = function() {
onmouseover
an element. handleMouseOver(); };
Event Description Example Usage
Occurs when the pointer is moved out javascript [Link] = function() {
onmouseout
of an element. handleMouseOut(); };

F. Form Events

Event Description Example Usage


onsubmit Occurs when a form is submitted. javascript [Link] = function() { handleSubmit(); };
onreset Occurs when a form is reset. javascript [Link] = function() { handleReset(); };

G. Media Events

Event Description Example Usage


javascript [Link] = function() {
onplay Occurs when the media begins to play.
handlePlay(); };
javascript [Link] = function() {
onpause Occurs when the media is paused.
handlePause(); };
Occurs when the media has reached the javascript [Link] = function() {
onended
end. handleEnded(); };
Occurs when the playing position of the javascript [Link] = function() {
ontimeupdate
media is changed. handleTimeUpdate(); };

 JavaScript – Cookies

In JavaScript, cookies are small pieces of data stored by the browser that can persist across sessions and be
sent back to the server with subsequent requests. They are primarily used for maintaining stateful
information such as user preferences, session identifiers, or tracking information. Here's a detailed overview
of how cookies work in JavaScript:

Working with Cookies in JavaScript

 Setting a Cookie

To set a cookie, you assign a string value to the [Link] property. Cookies are appended to
this property, separated by semicolons (;). Each cookie consists of a key-value pair, and optionally,
additional attributes like expiration date, domain, path, and security settings can be specified.

Example: Setting a Cookie

[Link] = "username=JohnDoe; expires=Tue, 19 Jan 2025 12:00:00 UTC; path=/";


 Key-Value Pair: username=JohnDoe
 Expires: expires=Tue, 19 Jan 2025 12:00:00 UTC (optional, specifies when the cookie expires)
 Path: path=/ (optional, specifies the path within the domain for which the cookie is valid)

 Getting a Cookie

To retrieve a specific cookie, you can parse the [Link] string or use a helper function to
extract the value associated with a specific key.

Example: Getting a Cookie

function getCookie(name) {
let cookies = [Link](';');
for (let cookie of cookies) {
let cookiePair = [Link]().split('=');
if (cookiePair[0] === name) {
return decodeURIComponent(cookiePair[1]);
}
}
return null;
}

let username = getCookie('username');


[Link](username); // Output: JohnDoe

 Deleting a Cookie
To delete a cookie, you can set its expiration date to a time in the past. This instructs the browser to
remove the cookie from its storage.

Example: Deleting a Cookie

[Link] = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

 Cookie Attributes

Cookies can have several attributes that modify their behavior:

 Expires/Max-Age: Specifies when the cookie should expire.


 Domain: Limits the cookie to a specific domain and its subdomains.
 Path: Limits the cookie to a specific path within the domain.
 Secure: Ensures the cookie is only sent over secure (HTTPS) connections.
 HttpOnly: Prevents JavaScript from accessing the cookie, enhancing security against cross-
site scripting (XSS) attacks.

Example: Setting Cookie Attributes

[Link] = "username=JohnDoe; expires=Tue, 19 Jan 2025 12:00:00 UTC; path=/;


domain
 JavaScript – Session

In JavaScript, sessions typically refer to the concept of maintaining user state across multiple pages of
a web application. Since JavaScript runs in the browser, sessions are managed using a combination of
cookies, sessionStorage, and localStorage.

 Overview of Session Management in JavaScript

 Cookies
Cookies are small pieces of data stored by the browser that can persist across sessions and pages.
They can be used to store user preferences, session tokens, etc.

Example: Setting and Getting Cookies

// Setting a cookie
[Link] = "username=JohnDoe; path=/; expires=Tue, 19 Jun 2024 12:00:00 UTC";

// Getting a cookie
function getCookie(name) {
let match = [Link](new RegExp('(^| )' + name + '=([^;]+)'));
if (match) {
return match[2];
} else {
return null;
}
}

[Link](getCookie("username")); // Output: JohnDoe

 sessionStorage
The sessionStorage object stores data for the duration of the page session. The data is deleted
when the page session ends (i.e., when the page is closed).

Example: Using sessionStorage

// Storing data
[Link]("username", "JohnDoe");

// Retrieving data
let username = [Link]("username");
[Link](username); // Output: JohnDoe

// Removing data
[Link]("username");

// Clearing all data


[Link]();

 localStorage
The localStorage object stores data with no expiration time. The data is available even after
the browser is closed and reopened.

Example: Using localStorage

// Storing data
[Link]("username", "JohnDoe");

// Retrieving data
let username = [Link]("username");
[Link](username); // Output: JohnDoe

// Removing data
[Link]("username");

// Clearing all data


[Link]();

 Comparison of Cookies, sessionStorage, and localStorage

Feature Cookies sessionStorage localStorage

Storage
4KB per cookie 5MB per origin 5MB per origin
Limit

Never (unless manually


Expiration Manually set expiration date When the page session ends
cleared)

Sent with every HTTP request Accessible only within the Accessible across tabs and
Accessibility
to the server current tab browser restarts

Domain-wide (or path-


Data Scope Tab-specific Domain-wide
specific)

 JavaScript – Page Redirect


Page redirection refers to the process of automatically navigating from one web page to another. It is
commonly used for directing users to different pages based on certain conditions or actions, such as after a
form submission, during site maintenance, or when moving to a new domain.

 JavaScript Page Refresh

You can refresh the current page using the [Link]() method. This method reloads the resource
from the current URL.

Example:

// Reload the current page


[Link]();

 Auto Refresh
Auto-refreshing a page can be achieved using the setTimeout() or setInterval() functions. These functions
allow you to execute code after a specified period or repeatedly at specified intervals, respectively.

Using setTimeout():

// Refresh the page every 5 seconds


setTimeout(function() {
[Link]();
}, 5000);

Using setInterval():

// Refresh the page every 5 seconds


setInterval(function() {
[Link]();
}, 5000);

 How Page Redirection Works

Page redirection can be accomplished using the [Link] object. You can set its href property to the
URL of the page you want to redirect to. This changes the current URL and loads the new page.

Example:

// Redirect to another page


[Link] = "[Link]

 17. JavaScript – Dialog Box


 Alert Dialog Box
An alert dialog box is used to display a message to the user. It only has an "OK" button and does not return
any value.

Example

// Display an alert dialog box


alert("Hello, World!");

When this code runs, a dialog box will appear with the message "Hello, World!" and an "OK" button. The
user must click "OK" to close the dialog box and continue.

 Confirmation Dialog Box

A confirmation dialog box is used to ask the user for confirmation. It has "OK" and "Cancel" buttons and
returns a boolean value: true if the user clicks "OK", and false if the user clicks "Cancel".

Example

// Display a confirmation dialog box


let result = confirm("Are you sure you want to delete this item?");
if (result) {
// Code to delete the item
[Link]("Item deleted.");
} else {
// Code to cancel delete operation
[Link]("Delete operation cancelled.");
}

In this example, if the user clicks "OK", the code inside the if (result) block will execute. If the user clicks
"Cancel", the code inside the else block will execute.

 Prompt Dialog Box

A prompt dialog box is used to ask the user to input text. It has an input field and "OK" and "Cancel"
buttons. It returns the input value as a string if the user clicks "OK", or null if the user clicks "Cancel".

Example
// Display a prompt dialog box
let name = prompt("Please enter your name:", "John Doe");
if (name != null) {
[Link]("Hello, " + name);
} else {
[Link]("User cancelled the prompt.");
}

In this example, if the user enters a name and clicks "OK", the input value is stored in the name variable, and
the message "Hello, [name]" is logged to the console. If the user clicks "Cancel", the message "User
cancelled the prompt." is logged.

 JavaScript – Void Keyword

The void keyword is used to evaluate an expression without returning a value. It is often used with
href attribute in anchor tags to prevent the browser from navigating to a new page:

Example:

<a href="javascript:void(0);" onclick="doSomething()">Click Here</a>

 19. JavaScript – Page Printing


How to Print a Page?

To print a webpage using JavaScript, you can utilize the [Link]() method. This method triggers
the browser's print dialog, allowing the user to print the current page. To make this functionality user-
friendly, you can add a button to your webpage that, when clicked, calls this method.

JavaScript Function to Print the Page

 Create a JavaScript function named printPage that calls [Link]().

Example:

// JavaScript function to print the current page


function printPage() {
[Link]();
}
HTML Button to Trigger Printing

 Add a button element in your HTML and set its onclick attribute to call the printPage function.

Example:

<!-- HTML button that triggers the printPage function -->


<button onclick="printPage()">Print Page</button>

Demo Example to print page using button

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Print Page Example</title>
<script>
// JavaScript function to print the current page
function printPage() {
[Link]();
}
</script>
</head>
<body>
<h1>Welcome to My Web Page</h1>
<p>This is a sample webpage content that you can print using the button below.</p>

<!-- HTML button that triggers the printPage function -->


<button onclick="printPage()">Print Page</button>
</body>
</html>

 JavaScript – Objects
In JavaScript, objects are used to model real-life entities with properties and methods. Let's delve
into how you can define, use, and manipulate objects in JavaScript.

Car Object Example

Car Object Properties and Methods:

Property Value

name Fiat

model 500

weight 850kg

color White
Method Description

start() Starts the car

drive() Drives the car


 JavaScript Variables and Objects
brake() Applies the brakes
 JavaScript Variables
stop() Stops the car
Variables are containers for storing data values.

Example:

let car = "Fiat";

 JavaScript Objects

Objects are variables too, but they can contain multiple values. They are defined using object
literals or constructors.

Example Using Object Literal:

const car = {
type: "Fiat",
model: "500",
color: "white"
};

 JavaScript Object Definition

 Using Object Literal

An object literal is a straightforward way to create objects using a list of name-value pairs inside
curly braces {}.

Example:

const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};

Example Spanning Multiple Lines:

const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};

 Using the new Keyword

You can create objects using the new keyword and an object constructor.
Example:

const person = new Object();


[Link] = "John";
[Link] = "Doe";
[Link] = 50;
[Link] = "blue";

Note: Using object literals is generally preferred for readability and performance.

 Object Properties

Properties are the values associated with a JavaScript object.

Example:

const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};

o Accessing Object Properties

You can access properties of an object in several ways:

1. Dot Notation:

let age = [Link];

2. Bracket Notation:

let age = person["age"];

3. Expression:

let age = person[x];

Examples:

[Link] + " is " + [Link] + " years old.";


person["firstName"] + " is " + person["age"] + " years old.";

o Adding New Properties

To add a new property to an existing object, simply assign a value to it:

Example:

[Link] = "English";

o Deleting Properties

Use the delete keyword to remove a property from an object:


Example:

const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};

delete [Link];

Alternative:

delete person["age"];

Note: The delete keyword removes both the property and its value. The property cannot be
accessed until it is re-added.

 JavaScript Object Methods

In JavaScript, methods are functions defined as properties of an object. They perform actions using the
object's properties and can be accessed and invoked using specific syntax.

o Defining and Accessing Object Methods

Example Object with Method

Let's consider an object person with a method fullName.

Example:

const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName: function() {
return [Link] + " " + [Link];
}
};

In this example:

 this refers to the person object.


 [Link] accesses the firstName property of the person object.
 [Link] accesses the lastName property of the person object.

o Accessing Object Methods

To access an object method, use the following syntax:

[Link]()

Example:
let name = [Link](); // "John Doe"

If you access the fullName property without parentheses (), it will return the function
definition instead of executing it.

Example:

let name = [Link]; // Returns the function definition

o Adding a Method to an Object

You can easily add new methods to an existing object.

Example:

[Link] = function() {
return [Link] + " " + [Link];
};

// Using the new method


[Link]([Link]()); // "John Doe"

o Using Built-in JavaScript Methods

You can also use JavaScript built-in methods within your object methods.

Example with toUpperCase() Method:

[Link] = function() {
return ([Link] + " " + [Link]).toUpperCase();
};

// Using the modified method


[Link]([Link]()); // "JOHN DOE"

 21. JavaScript – Number


 Number Properties

The JavaScript Number object has several properties that provide important information about
numeric values.

Property Description Example

Represents the largest


MAX_VALUE [Link](Number.MAX_VALUE);
possible numeric value.

Represents the smallest


MIN_VALUE [Link](Number.MIN_VALUE);
possible numeric value.
Property Description Example

Represents "Not-a-
NaN [Link]([Link]);
Number" value.

Represents negative
NEGATIVE_INFINITY [Link](Number.NEGATIVE_INFINITY);
infinity.

Represents positive
POSITIVE_INFINITY [Link](Number.POSITIVE_INFINITY);
infinity.

A. Prototype

The prototype property allows you to add properties and methods to the Number object.

Property Description Example

Allows the addition of properties [Link] = function()


prototype
and methods to Number object. { return this > 0; };

B. Constructor

The constructor property returns the constructor function for a Number object.

Property Description Example

Returns the constructor function for a let num = 123;


constructor
Number object. [Link]([Link]);

 Number Methods
The Number object has several built-in methods for performing operations on numbers.

Method Description Example

Converts a number to exponential


toExponential(fractionDigits) [Link]([Link](2));
notation.

Formats a number using fixed-


toFixed(digits) [Link]([Link](1));
point notation.

Converts a number to a string


toLocaleString() [Link]([Link]());
using locale-specific formatting.

Formats a number to a specified


toPrecision(precision) [Link]([Link](3));
length.

Converts a number to a string in a


toString(radix) [Link]([Link](16));
specified base (radix).
Method Description Example

Returns the primitive value of a


valueOf() [Link]([Link]());
Number object.

Example

let num = 123.456;

[Link]([Link](2)); // Output: 1.23e+2


[Link]([Link](1)); // Output: 123.5
[Link]([Link]()); // Output: 123.456 (depends on locale)
[Link]([Link](3)); // Output: 123
[Link]([Link](16)); // Output: 7b.74ae147ae147bp+6
[Link]([Link]()); // Output: 123.456

[Link] = function() {
return this % 2 === 0;
};

[Link]((2).isEven()); // Output: true

 JavaScript – Boolean
 Boolean Properties
The Boolean object has a few key properties, primarily constructor and prototype.

Property Description Example

Returns the constructor function for a let bool = true;


constructor
Boolean object. [Link]([Link]);

Allows addition of properties and [Link] = function() {


prototype
methods to the Boolean object. return [Link]() === true; };

 Boolean Methods
The Boolean object has several methods for operations on boolean values.

Method Description Example

Returns a string representing the source code of let bool = true;


toSource()
the object. (Non-standard) [Link]([Link]());

toString() Converts a Boolean value to a string. [Link]([Link]());

valueOf() Returns the primitive value of a Boolean object. [Link]([Link]());

Example
let bool = true;

[Link]([Link]()); // Output: true (Non-standard, may not be supported in all


environments)
[Link]([Link]()); // Output: true
[Link]([Link]()); // Output: true

[Link] = function() {
return ![Link]();
};

let newBool = new Boolean(true);


[Link]([Link]()); // Output: false

 JavaScript – String
A JavaScript string is zero or more characters written inside quotes.

 String Properties

The String object has several key properties.

Property Description Example


Returns the constructor function for a
constructor let str = "Hello"; [Link]([Link]);
String object.

length Returns the length of the string. let str = "Hello"; [Link]([Link]);

Allows the addition of properties and [Link] = function() { return


prototype
methods to String object. "Hello, " + this; };

 String Methods
String object has many methods for manipulating strings.

Method Description Example

charAt(index) Returns the character at the specified index. [Link](0)

Returns the Unicode of the character at the


charCodeAt(index) [Link](0)
specified index.

at(index) Returns the character at the specified index. [Link](0)

Accesses the character at the specified


[index] str[0]
index (similar to charAt).
Extracts a part of a string and returns it as a
slice(start, end) [Link](0, 5)
new string.
Method Description Example
Returns the part of the string between the
substring(start, end) [Link](1, 4)
start and end indexes.
Returns a part of the string, starting at the
substr(start, length) specified index and extending for a given [Link](7, 5)
number of characters.
toUpperCase() Converts the string to uppercase letters. [Link]()
toLowerCase() Converts the string to lowercase letters. [Link]()
Joins two or more strings and returns a new
concat(str2, ...) [Link](" Goodbye")
string.
Removes whitespace from both ends of the
trim() [Link]()
string.
Removes whitespace from the beginning of
trimStart() [Link]()
the string.
Removes whitespace from the end of the
trimEnd() [Link]()
string.
Pads the current string with another string
padStart(targetLength,
from the start, until the resulting string [Link](15, ".")
padString)
reaches the given length.
Pads the current string with another string
padEnd(targetLength,
from the end, until the resulting string [Link](15, ".")
padString)
reaches the given length.
Returns a new string with a specified
repeat(count) [Link](2)
number of copies of the original string.
replace(searchValue, Replaces a specified value with another [Link]("World",
newValue) value in the string. "Alice")
replaceAll(searchValue, Replaces all occurrences of a specified
[Link]("l", "L")
newValue) value with another value in the string.

split(separator, limit) Splits the string into an array of substrings. [Link](", ")

indexOf(searchValue, Returns the index of the first occurrence of


[Link]("World")
fromIndex) a specified value.
lastIndexOf(searchValue, Returns the index of the last occurrence of a
[Link]("l")
fromIndex) specified value.
Retrieves the result of matching a string
match(regex) [Link](/lo/g)
against a regular expression.
Searches for a match between a regular
search(regex) [Link]("World")
expression and this String object.
Returns the primitive value of a String
valueOf() [Link]()
object.

Example

let str = "Hello, World!";


[Link]([Link](0)); // Output: H
[Link]([Link](0)); // Output: 72
[Link]([Link](" Goodbye")); // Output: Hello, World! Goodbye
[Link]([Link]("World")); // Output: 7
[Link]([Link]("l")); // Output: 10
[Link]([Link](/lo/g)); // Output: ['lo', 'lo']
[Link]([Link]("World", "Alice")); // Output: Hello, Alice!
[Link]([Link]("World")); // Output: 7
[Link]([Link](0, 5)); // Output: Hello
[Link]([Link](", ")); // Output: ['Hello', 'World!']
[Link]([Link](7, 5)); // Output: World
[Link]([Link](1, 4)); // Output: ell
[Link]([Link]()); // Output: hello, world!
[Link]([Link]()); // Output: HELLO, WORLD!
[Link]([Link]()); // Output: Hello, World!

 String HTML Wrappers


The String object in JavaScript has several methods specifically designed for creating HTML strings for
various text formatting purposes. These methods wrap the original string in HTML tags to format the text
accordingly.

HTML Wrapper Methods

Method Description Example

anchor(name) Creates an HTML anchor (<a>) that is used as a hyperlink. [Link]("name")

big() Displays a string in a large font (<big>). [Link]()

blink() Displays a string as blinking text (<blink>). (Deprecated) [Link]()

bold() Displays a string as bold text (<b>). [Link]()

fixed() Displays a string in a fixed-width font (<tt>). [Link]()

fontcolor(color) Displays a string in the specified color. [Link]("red")

fontsize(size) Displays a string in the specified font size. [Link](5)

italics() Displays a string as italic text (<i>). [Link]()

Creates an HTML hyperlink (<a>) that links to the


link(url) [Link]("[Link]
specified URL.

small() Displays a string in a small font (<small>). [Link]()

strike() Displays a string with a strikethrough (<strike>). [Link]()

sub() Displays a string as subscript text (<sub>). [Link]()

sup() Displays a string as superscript text (<sup>). [Link]()


Example

let str = "Hello, World!";


[Link]([Link]("myAnchor")); // Output: <a name="myAnchor">Hello, World!</a>
[Link]([Link]()); // Output: <big>Hello, World!</big>
[Link]([Link]()); // Output: <blink>Hello, World!</blink> (Deprecated)
[Link]([Link]()); // Output: <b>Hello, World!</b>
[Link]([Link]()); // Output: <tt>Hello, World!</tt>
[Link]([Link]("red")); // Output: <font color="red">Hello, World!</font>
[Link]([Link](5)); // Output: <font size="5">Hello, World!</font>
[Link]([Link]()); // Output: <i>Hello, World!</i>
[Link]([Link]("[Link] // Output: <a href="[Link]
World!</a>
[Link]([Link]()); // Output: <small>Hello, World!</small>
[Link]([Link]()); // Output: <strike>Hello, World!</strike>
[Link]([Link]()); // Output: <sub>Hello, World!</sub>
[Link]([Link]()); // Output: <sup>Hello, World!</sup>

 24. JavaScript – Arrays


Overview
An array is a special variable that can hold more than one value at a time. This makes it easy to store
collections of data under a single variable name and access elements via index numbers.

 Why Use Arrays?


Arrays simplify the process of handling lists of items. For example, instead of storing multiple
car names in separate variables, you can store them in a single array and access them via their
index.

let car1 = "Saab";


let car2 = "Volvo";
let car3 = "BMW";
// versus
const cars = ["Saab", "Volvo", "BMW"];

 Creating an Array
Arrays can be created using array literals or the new Array() constructor.

 Using Array Literals:


const cars = ["Saab", "Volvo", "BMW"];

This can be spread over multiple lines for better readability:

const cars = [
"Saab",
"Volvo",
"BMW"
];

 Using new Array():


const cars = new Array("Saab", "Volvo", "BMW");

Providing Elements After Creation:

const cars = [];


cars[0] = "Saab";
cars[1] = "Volvo";
cars[2] = "BMW";

Note: Using the array literal is generally preferred for simplicity and readability.

 Accessing Array Elements


Elements are accessed via their index, starting from 0.

const cars = ["Saab", "Volvo", "BMW"];


let car = cars[0]; // "Saab"

 Changing an Array Element

Elements can be changed by assigning a new value to an index.

cars[0] = "Opel";

 Converting an Array to a String


The toString() method converts an array to a comma-separated string.

const fruits = ["Banana", "Orange", "Apple", "Mango"];


[Link]("demo").innerHTML = [Link]();
// Output: "Banana,Orange,Apple,Mango"

 Accessing the Full Array


The entire array can be accessed by referring to the array name.

const cars = ["Saab", "Volvo", "BMW"];


[Link]("demo").innerHTML = cars;

Arrays are Objects

Arrays in JavaScript are objects with numbered indexes, making them different from regular objects,
which use named indexes.

const personArray = ["John", "Doe", 46]; // Array with numbered indexes


const personObject = {firstName: "John", lastName: "Doe", age: 46}; // Object with named indexes

Array Elements Can Be Objects

JavaScript arrays can hold elements of various types, including other arrays, functions, and objects.

const myArray = [];


myArray[0] = [Link];
myArray[1] = myFunction;
myArray[2] = myCars;

 Array Properties and Methods


 Array Properties

Property Description
index Represents zero based index.
length Returns the number of elements in the array.

 Array Methods

Method Description
toString() Converts the array to a string of comma-separated values.
at() Returns the element at a specified index in the array.
join() Joins all elements of the array into a string.
pop() Removes the last element from the array and returns it.
push() Adds one or more elements to the end of the array.
shift() Removes the first element from the array and returns it.
unshift() Adds one or more elements to the beginning of the array.
delete() Deletes elements from an array at a specific index.
concat() Returns a new array by combining existing arrays.
copyWithin() Copies a sequence of elements within the array.
Creates a new array with all sub-array elements concatenated into it recursively up
flat()
to a specified depth.
splice() Adds or removes elements from an array.
slice() Extracts a section of an array and returns a new array.
every() Tests whether all elements in the array pass a provided function.
Creates a new array with all elements that pass a test implemented by a provided
filter()
function.
forEach() Executes a provided function once for each array element.
indexOf() Returns the first index at which a given element can be found.
lastIndexOf() Returns the last index at which a given element can be found.
Creates a new array with the results of calling a provided function on every
map()
element.
Applies a function against an accumulator and each array element (from left to
reduce()
right) to reduce it to a single value.
Applies a function against an accumulator and each array element (from right to
reduceRight()
left) to reduce it to a single value.
reverse() Reverses the order of the elements in an array.
some() Tests whether at least one element in the array passes a provided function.
sort() Sorts the elements of an array in place and returns the array.
toLocaleString() Returns a string representing the elements of the array in locale-sensitive format.
find() Returns the value of the first element that satisfies the provided testing function.
findIndex() Returns the index of the first element that satisfies the provided testing function.
Example

let arr = [1, 2, 3, 4, 5];


[Link]([Link]([6, 7])); // Output: [1, 2, 3, 4, 5, 6, 7]
[Link]([Link](num => num > 0)); // Output: true
[Link]([Link](num => num > 2)); // Output: [3, 4, 5]
[Link](num => [Link](num)); // Output: 1 2 3 4 5
[Link]([Link](3)); // Output: 2
[Link]([Link](", ")); // Output: "1, 2, 3, 4, 5"
[Link]([Link](4)); // Output: 3
[Link]([Link](num => num * 2)); // Output: [2, 4, 6, 8, 10]
[Link]([Link]()); // Output: 5 (removes and returns last element)
[Link]([Link](6)); // Output: 6 (adds element and returns new length)
[Link]([Link]((acc, num) => acc + num)); // Output: 15 (sum of all elements)
[Link]([Link]((acc, num) => acc - num)); // Output: -13 (right-to-left reduce)
[Link]([Link]()); // Output: [5, 4, 3, 2, 1]
[Link]([Link]()); // Output: 5 (removes and returns first element)
[Link]([Link](1, 3)); // Output: [4, 3] (returns shallow copy of elements)
[Link]([Link](num => num > 2)); // Output: true
[Link]([Link]()); // Output: [1, 2, 3, 4, 5] (sorted ascending)
[Link]([Link](2, 1, 0)); // Output: [3] (removes 1 element at index 2 and adds 0)
[Link]([Link]()); // Output: "1, 2, 0, 4, 5" (string representation)
[Link]([Link](-1)); // Output: 6 (adds element to beginning and returns new
length)

 Array Loops

H. Using for Loop:

const fruits = ["Banana", "Orange", "Apple", "Mango"];


let fLen = [Link];

let text = "<ul>";


for (let i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";

I. Using forEach():

const fruits = ["Banana", "Orange", "Apple", "Mango"];

let text = "<ul>";


[Link](function(value) {
text += "<li>" + value + "</li>";
});
text += "</ul>";

 Adding Array Elements

A. Using push():

const fruits = ["Banana", "Orange", "Apple"];


[Link]("Lemon"); // Adds a new element (Lemon) to fruits

B. Using length Property:

const fruits = ["Banana", "Orange", "Apple"];


fruits[[Link]] = "Lemon"; // Adds "Lemon" to fruits

 Avoid Creating Undefined Holes:


const fruits = ["Banana", "Orange", "Apple"];
fruits[6] = "Lemon"; // Creates undefined "holes" in fruits

 Recognizing Arrays

A. Using [Link]():

const fruits = ["Banana", "Orange", "Apple"];


[Link](fruits); // Returns true

B. Using instanceof Operator:

const fruits = ["Banana", "Orange", "Apple"];


(fruits instanceof Array); // Returns true

 Nested Arrays and Objects


Arrays and objects can be nested within each other, enabling complex data structures.

const myObj = {
name: "John",
age: 30,
cars: [
{name:"Ford", models:["Fiesta", "Focus", "Mustang"]},
{name:"BMW", models:["320", "X3", "X5"]},
{name:"Fiat", models:["500", "Panda"]}
]
};

for (let i in [Link]) {


let car = [Link][i];
[Link]([Link]);
for (let j in [Link]) {
[Link]([Link][j]);
}
}

 JavaScript – Date
The Date object in JavaScript is used to work with dates and times. It provides various methods and
properties to get and set date and time components.

Creating a Date Object

You can create a new date object using the Date constructor:

let now = new Date();


[Link](now); // Output: current date and time

 Date Properties
The Date object in JavaScript has various properties such as constructor, prototype, and methods for
getting and setting date and time components.

Property Description
constructor Returns the function that created the Date object's prototype.
prototype Allows you to add properties and methods to a Date object.

 Date Methods
Date object methods allow manipulation and retrieval of date and time information.

 Getting Date and Time Components

Method Description Example Usage Example Output

getDate() Gets the day of the month (1-31). [Link]() 1-31

getDay() Gets the day of the week (0-6). [Link]() 0-6 (0 is Sunday)

getFullYear() Gets the full year (e.g., 2024). [Link]() 2024

getHours() Gets the hour (0-23). [Link]() 0-23

getMilliseconds() Gets the milliseconds (0-999). [Link]() 0-999

getMinutes() Gets the minutes (0-59). [Link]() 0-59

getMonth() Gets the month (0-11, 0 is January). [Link]() 0-11

getSeconds() Gets the seconds (0-59). [Link]() 0-59

Gets the timestamp (milliseconds since milliseconds since Unix


getTime() [Link]()
Unix epoch). epoch

offset in minutes (e.g., -480


getTimezoneOffset() Gets the timezone offset in minutes. [Link]()
for PST)

getUTCDate() Gets the UTC day of the month (1-31). [Link]() 1-31

getUTCDay() Gets the UTC day of the week (0-6). [Link]() 0-6 (0 is Sunday)
Method Description Example Usage Example Output

getUTCFullYear() Gets the UTC full year (e.g., 2024). [Link]() 2024

getUTCHours() Gets the UTC hour (0-23). [Link]() 0-23

getUTCMilliseconds() Gets the UTC milliseconds (0-999). [Link]() 0-999

getUTCMinutes() Gets the UTC minutes (0-59). [Link]() 0-59

Gets the UTC month (0-11, 0 is


getUTCMonth() [Link]() 0-11
January).

getUTCSeconds() Gets the UTC seconds (0-59). [Link]() 0-59

getYear() Gets the year minus 1900 (deprecated). [Link]() year minus 1900

Setting Date and Time Components

Method Description Example Usage Example Output

setDate(day) Sets the day of the month (1-31). [Link](15) Updated date object

setFullYear(year) Sets the full year (e.g., 2025). [Link](2025) Updated date object

setHours(hours) Sets the hour (0-23). [Link](20) Updated date object

setMilliseconds(ms) Sets milliseconds (0-999). [Link](500) Updated date object

setMinutes(minutes) Sets the minutes (0-59). [Link](45) Updated date object

Sets the month (0-11, 0 is


setMonth(month) [Link](5) Updated date object
January).

setSeconds(seconds) Sets the seconds (0-59). [Link](30) Updated date object

setTime(millisecond Sets the time (milliseconds since


[Link]([Link]()) Updated date object
s) Unix epoch).

Sets the UTC day of the month


setUTCDate(day) [Link](20) Updated date object
(1-31).

setUTCFullYear(yea Sets the UTC full year (e.g., [Link](202


Updated date object
r) 2023). 3)

setUTCHours(hours) Sets the UTC hour (0-23). [Link](18) Updated date object

setUTCMilliseconds Sets the UTC milliseconds (0- [Link](


Updated date object
(ms) 999). 400)

setUTCMinutes(min
Sets the UTC minutes (0-59). [Link](30) Updated date object
utes)
Method Description Example Usage Example Output

setUTCMonth(mont Sets the UTC month (0-11, 0 is


[Link](4) Updated date object
h) January).

setUTCSeconds(sec
Sets the UTC seconds (0-59). [Link](15) Updated date object
onds)

Sets the year minus 1900


setYear(year) [Link](100) Updated date object
(deprecated).

let now = new Date();


[Link]([Link]()); // Output: Current day of the month (1-31)
[Link]([Link]()); // Output: Current day of the week (0-6)
[Link]([Link]()); // Output: Current year (e.g., 2024)
[Link]([Link]()); // Output: Current hour (0-23)
[Link]([Link]()); // Output: Current milliseconds (0-999)
[Link]([Link]()); // Output: Current minutes (0-59)
[Link]([Link]()); // Output: Current month (0-11)
[Link]([Link]()); // Output: Current seconds (0-59)
[Link]([Link]()); // Output: Current timestamp (milliseconds since Unix epoch)
[Link]([Link]()); // Output: Timezone offset in minutes (e.g., -480 for PST)
[Link]([Link]()); // Output: Current UTC day of the month (1-31)
[Link]([Link]()); // Output: Current UTC day of the week (0-6)
[Link]([Link]()); // Output: Current UTC year (e.g., 2024)
[Link]([Link]()); // Output: Current UTC hour (0-23)
[Link]([Link]());// Output: Current UTC milliseconds (0-999)
[Link]([Link]()); // Output: Current UTC minutes (0-59)
[Link]([Link]()); // Output: Current UTC month (0-11)
[Link]([Link]()); // Output: Current UTC seconds (0-59)
[Link]([Link]()); // Output: Current year minus 1900 (deprecated)

Methods like setDate(), setFullYear(), setHours(), setMilliseconds(), setMinutes(), setMonth(), setSeconds(),


setTime(), setUTCDate(), setUTCFullYear(), setUTCHours(), setUTCMilliseconds(), setUTCMinutes(),
setUTCMonth(), setUTCSeconds(), and setYear() allow setting these respective components of a Date
object.

 JavaScript – Math
The Math object in JavaScript provides properties and methods for mathematical constants and
functions.

 Math Properties

Property Description Value


E Euler's number 2.718281828459045
LN2 Natural logarithm of 2 0.6931471805599453
LN10 Natural logarithm of 10 2.302585092994046
LOG2E Base 2 logarithm of E 1.4426950408889634
LOG10E Base 10 logarithm of E 0.4342944819032518
PI Pi 3.141592653589793
Property Description Value
SQRT1_2 Square root of 1/2 0.7071067811865476
SQRT2 Square root of 2 1.4142135623730951

 Math Methods

Example
Method Description Example Output
Usage
[Link](x) Returns the absolute value of a number. [Link](-5) 5
[Link](x) Returns the arccosine of a number. [Link](0.5) 1.0471975511965976
[Link](x) Returns the arcsine of a number. [Link](0.5) 0.5235987755982989
[Link](x) Returns the arctangent of a number. [Link](0.5) 0.4636476090008061
Returns the arctangent of the quotient of its
Math.atan2(y, x) Math.atan2(1, 2) 0.4636476090008061
arguments.
Returns the smallest integer greater than or
[Link](x) [Link](1.2) 2
equal to a number.
[Link](x) Returns the cosine of a number. [Link]([Link]) -1
[Link](x) Returns E^x, where x is the argument. [Link](1) 2.718281828459045
Returns the largest integer less than or equal
[Link](x) [Link](1.9) 1
to a number.
Returns the natural logarithm (base E) of a
[Link](x) [Link](Math.E) 1
number.
[Link](a, b,
...)
Returns the largest of zero or more numbers. [Link](1, 2, 3) 3
[Link](a, b, Returns the smallest of zero or more
...)
[Link](1, 2, 3) 1
numbers.
[Link](x, y) Returns x to the power of y. [Link](2, 3) 8
Returns a pseudo-random number between 0 Random number between 0
[Link]() [Link]()
and 1. and 1
Returns the value of a number rounded to
[Link](x) [Link](1.5) 2
the nearest integer.
[Link](x) Returns the sine of a number. [Link]([Link]) 0
[Link](x) Returns the square root of a number. [Link](4) 2
[Link](x) Returns the tangent of a number. [Link]([Link]) 0

Example

let now = new Date();


[Link]([Link]()); // Output: Current day of the month (1-31)
[Link]([Link]()); // Output: Current day of the week (0-6)
[Link]([Link]()); // Output: Current year (e.g., 2024)
[Link]([Link]()); // Output: Current hour (0-23)
[Link]([Link]()); // Output: Current milliseconds (0-999)
[Link]([Link]()); // Output: Current minutes (0-59)
[Link]([Link]()); // Output: Current month (0-11)
[Link]([Link]()); // Output: Current seconds (0-59)
[Link]([Link]()); // Output: Current timestamp (milliseconds since Unix epoch)
[Link]([Link]()); // Output: Timezone offset in minutes (e.g., -480 for PST)
[Link]([Link]()); // Output: Current UTC day of the month (1-31)
[Link]([Link]()); // Output: Current UTC day of the week (0-6)
[Link]([Link]()); // Output: Current UTC year (e.g., 2024)
[Link]([Link]()); // Output: Current UTC hour (0-23)
[Link]([Link]());// Output: Current UTC milliseconds (0-999)
[Link]([Link]()); // Output: Current UTC minutes (0-59)
[Link]([Link]()); // Output: Current UTC month (0-11)
[Link]([Link]()); // Output: Current UTC seconds (0-59)
[Link]([Link]()); // Output: Current year minus 1900 (deprecated)

 JavaScript RegExp
The RegExp object in JavaScript is used for matching text with a pattern. This can be done through
various properties and methods. Regular expressions (RegExp) in JavaScript are patterns used to match
character combinations in strings. They can be used for searching, replacing, extracting, and validating
string data. JavaScript supports regular expressions through the RegExp object and the String methods
that utilize it.

Here's a table listing some of the most commonly used characters in regular expressions along with
examples:

Character Description Example Pattern Example Match

. Matches any character except newline /a.c/ "abc", "a1c", "a-c"

\d Matches any digit (0-9) /\d/ "2", "7"

\D Matches any non-digit /\D/ "a", "-", " "

Matches any word character


\w /\w/ "a", "1", "_"
(alphanumeric or _)

\W Matches any non-word character /\W/ " ", "-", "!"

\s Matches any whitespace character /\s/ " ", "\t", "\n"

\S Matches any non-whitespace character /\S/ "a", "1", "!"

^ Matches the start of a string /^a/ "apple", "avocado"

$ Matches the end of a string /a$/ "banana", "cuba"

Matches 0 or more repetitions of the


* /a*/ "aa", "", "aaaa"
preceding char

Matches 1 or more repetitions of the


+ /a+/ "a", "aaa"
preceding char

Matches 0 or 1 repetition of the


? /a?/ "a", ""
preceding char
Character Description Example Pattern Example Match

"aa", "aaa" (matches first


{n} Matches exactly n occurrences /a{2}/
2)

{n,} Matches n or more occurrences /a{2,}/ "aa", "aaa", "aaaa"

{n,m} Matches between n and m occurrences /a{2,3}/ "aa", "aaa"

Matches either the pattern


` ` `/a
before or after

Matches any one of the enclosed


[...] /[aeiou]/ "a", "e", "i"
characters

Matches any character not in the


[^...] /[^aeiou]/ "b", "c", "d"
brackets

() Groups patterns /(abc)+/ "abc", "abcabc"

(?:...) Non-capturing group /(?:abc)+/ "abc", "abcabc"

(?=...) Positive lookahead /\d(?=px)/ "2" (in "2px")

(?!...) Negative lookahead /\d(?!px)/ "2" (not followed by "px")

\b Matches a word boundary /\bword\b/ "word", "a word in"

\B Matches a non-word boundary /\Bword\B/ "swordplay"

Examples

1. Dot Character (.):


o Pattern: /a.c/
o Matches: "abc", "a1c", "a-c"
o Non-matches: "ac", "abbc"
2. Digit Character (\d):
o Pattern: /\d/
o Matches: "2", "7"
o Non-matches: "a", "-"
3. Word Boundary (\b):
o Pattern: /\bword\b/
o Matches: "word", "a word in"
o Non-matches: "sword", "wordplay"
4. Character Classes ([...]):
o Pattern: /[aeiou]/
o Matches: "a", "e", "i"
o Non-matches: "b", "c"
5. Quantifiers (*, +, {n,m}):
o Pattern: /a*/
 Matches: "aa", "", "aaaa"
o Pattern: /a+/
 Matches: "a", "aaa"
o Pattern: /a{2,3}/

Matches: "aa", "aaa"

Non-matches: "a", "aaaa"
6. Anchors (^, $):
o Pattern: /^a/
 Matches: "apple", "avocado"
 Non-matches: "banana", "grape"
o Pattern: /a$/
 Matches: "banana", "cuba"
 Non-matches: "apple", "grape"

 RegExp Properties

Property Description Example Usage Example Output

constructor Returns the function that created the RegExp object. [Link] function RegExp

global Indicates if the "g" modifier is set. [Link] false

ignoreCase Indicates if the "i" modifier is set. [Link] true

lastIndex The index at which to start the next match. [Link] 0

multiline Indicates if the "m" modifier is set. [Link] false

source Returns the text of the RegExp pattern. [Link] hello

 RegExp Methods

Method Description Example Usage Example Output

Executes a search for a match in a string. [Link]("Hello ['Hello', index: 0, input:


exec()
Returns an array of information or null. World") 'Hello World']

Tests for a match in a string. Returns true or [Link]("Hello


test() true
false. World")

Example Code

let pattern = /hello/i;


[Link]([Link]("Hello World")); // Output: ['Hello', index: 0, input: 'Hello World']
[Link]([Link]("Hello World")); // Output: true

 RegExp Properties and Methods in Detail

 RegExp Properties
A. constructor: Specifies the function that creates an object's prototype.

[Link]([Link]); // Output: function RegExp() { [native code] }


B. global: Indicates whether the "g" flag is used.

let patternGlobal = /hello/g;


[Link]([Link]); // Output: true

C. ignoreCase: Indicates whether the "i" flag is used.

[Link]([Link]); // Output: true

D. lastIndex: Specifies the index at which to start the next match.

let patternWithGlobal = /hello/gi;


[Link]("Hello Hello");
[Link]([Link]); // Output: 5

E. multiline: Indicates whether the "m" flag is used.

let patternMultiline = /hello/m;


[Link]([Link]); // Output: true

F. source: Returns the text of the pattern.

[Link]([Link]); // Output: "hello"

 RegExp Methods
 exec(): Executes a search for a match in a string and returns the matched text along with
the position and input string.

let match = [Link]("Hello World");


[Link](match); // Output: ['Hello', index: 0, input: 'Hello World']

 test(): Tests for a match in a string and returns true or false.

let isMatch = [Link]("Hello World");


[Link](isMatch); // Output: true

 JavaScript DOM (Document Object Model)


The Document Object Model (DOM) is a programming interface for web documents. It represents the
page so that programs can change the document structure, style, and content. The DOM represents the
document as nodes and objects, which can be manipulated with a scripting language like [Link]
document object is the root of the DOM. It provides access to all the elements within a web page. Below
is a comprehensive overview of the document object, its properties, and methods.

 Types of DOM

1. Legacy DOM:
o Represents older DOM implementations.
o Used by older browsers and versions.

2. W3C DOM:
o Stands for World Wide Web Consortium DOM.
o Standardized interface.
o Provides methods and properties for accessing and manipulating documents.
3. IE 4 DOM:
o Specific to older versions of Internet Explorer.
o Includes methods and properties tailored for compatibility with IE 4.

Key Concepts

 Nodes: Every element, attribute, and piece of text in the HTML document is a node.
 Elements: HTML tags become elements in the DOM.
 Attributes: Additional properties and metadata associated with elements.
 Methods: Functions provided by the DOM for interacting with elements.
 Properties: Attributes of DOM nodes and elements.

 DOM Compatibility

Ensuring DOM compatibility is crucial for consistent behavior across different browsers. Modern
web development uses feature detection and polyfills to maintain compatibility across various
browsers and versions.

Example

// Accessing an element by ID and modifying its content


let element = [Link]('myElement');
[Link] = 'Updated content';

 Overview of the document Object


 Properties

Property Description Example


Returns the <body> element of [Link] =
[Link]
the document 'blue';
Returns the <head> element of
[Link] [Link]([Link]);
the document
Gets or sets the title of the
[Link] [Link] = 'New Title';
document
Returns the full URL of the
[Link] [Link]([Link]);
document
Returns the domain name of the
[Link] [Link]([Link]);
document
Returns the URI of the document
[Link] [Link]([Link]);
that linked to this document
Gets or sets the cookies
[Link] [Link] = "username=John Doe";
associated with the document
Returns the loading status of the
[Link] [Link]([Link]);
document
[Link] Returns the <html> element [Link]([Link]);
Returns a collection of all <a>
[Link] elements in the document that [Link]([Link]);
have a name attribute
Property Description Example
Returns a collection of all
[Link] <form> elements in the [Link]([Link]);
document
Returns a collection of all <img>
[Link] [Link]([Link]);
elements in the document
Returns a collection of all <a>
[Link] elements in the document that [Link]([Link]);
have an href attribute
Returns a collection of all
[Link] <script> elements in the [Link]([Link]);
document
Returns a list of all the style
[Link] [Link]([Link]);
sheets applied to the document

 Methods

Method Description Example


Returns the element with the
[Link](id) [Link]('myId');
specified id
Returns a collection of all
[Link](t [Link]('d
elements with the specified
agName) iv');
tag name
Returns a collection of all
[Link] [Link]('
elements with the specified
(name) myClass');
class name
Returns the first element that
[Link](selector) matches a specified CSS [Link]('.myClass');
selector
Returns a list of all elements
[Link]('.myClass'
[Link](selector) that match a specified CSS
);
selector
Creates a new element with
[Link](tagName) [Link]('div');
the specified tag name
Creates a new text node with [Link]('Hello
[Link](text)
the specified text World');
Writes HTML expressions or
[Link]('<h1>Hello
[Link](text) JavaScript code to a
World</h1>');
document
Adds a node to the end of the
[Link](newDiv)
[Link](node) list of children of a specified
;
parent node
Removes a child node from [Link](existing
[Link](node)
the DOM Div);
[Link](newNode, Replaces a child node with a [Link](newDiv,
oldNode) new node oldDiv);

Example

1. Changing the Content of an Element


<!DOCTYPE html>
<html>
<body>

<p id="demo">Hello World!</p>

<script>
[Link]("demo").innerHTML = "Hello JavaScript!";
</script>

</body>
</html>

2. Creating a New Element and Adding it to the DOM

<!DOCTYPE html>
<html>
<body>

<div id="div1">This is a div</div>

<script>
let newParagraph = [Link]("p");
[Link] = "This is a new paragraph.";
[Link]("div1").appendChild(newParagraph);
</script>

</body>
</html>

3. Writing Directly to the Document

<!DOCTYPE html>
<html>
<body>
<script>
[Link]("This is written directly to the document.");
</script>

</body>
</html>

 JavaScript Window Object


The window object in JavaScript represents the browser's window. It's the global object in client-
side JavaScript, meaning all global variables, functions, and objects automatically become members
of the window object. The window object provides methods to control the browser window,
navigate, manipulate documents, and much more.

 Overview of the window Object


 Properties
Property Description Example
Returns the interior width of the
[Link] [Link]([Link]);
window in pixels
Returns the interior height of the
[Link] [Link]([Link]);
window in pixels
Returns the Location object with
[Link] [Link]([Link]);
information about the current URL
Returns the document object for the
[Link] [Link]([Link]);
window
Returns the History object for the
[Link] [Link]([Link]);
window
Returns the Navigator object with
[Link] [Link]([Link]);
information about the browser
Returns the Screen object with
[Link] [Link]([Link]);
information about the user's screen
Provides access to the web storage
[Link] [Link]('key', 'value');
object for local storage
Provides access to the web storage [Link]('key',
[Link]
object for session storage 'value');
Returns all frame elements in the
[Link] [Link]([Link]);
window
[Link] Returns the parent window [Link]([Link]);
Returns a reference to the window
[Link] [Link]([Link]);
that opened the current window
Returns the topmost window in the
[Link] [Link]([Link]);
hierarchy

 Methods

Method Description Example


Displays an alert box with a
[Link]() specified message and an [Link]('Hello!');
OK button
Displays a dialog box with a
[Link]() message and OK and Cancel let result = [Link]('Are you sure?');
buttons
Displays a dialog box that
[Link]() let name = [Link]('Enter your name:');
prompts the user for input
Opens a new browser
[Link]() [Link]('[Link]
window or tab
[Link]() Closes the current window [Link]();
Prints the content of the
[Link]() [Link]();
current window
Scrolls the document to the
[Link]() [Link](0, 100);
specified coordinates
Calls a function or evaluates
[Link]() [Link](() => { alert('Hello!'); }, 2000);
an expression after a
Method Description Example
specified number of
milliseconds
Calls a function or evaluates
[Link](() => { [Link]('Hello!'); },
[Link]() an expression at specified
1000);
intervals
Clears a timer set with let timerId = [Link](() => {}, 2000);
[Link]()
setTimeout() [Link](timerId);
Clears a timer set with let intervalId = [Link](() => {}, 1000);
[Link]()
setInterval() [Link](intervalId);
Sets focus on the current
[Link]() [Link]();
window
Removes focus from the
[Link]() [Link]();
current window

Example Usage

1. Display an Alert

[Link]('This is an alert box!');

2. Open a New Window

[Link]('[Link] '_blank');

3. Scroll the Window

[Link](0, 500); // Scrolls the document to 500 pixels from the top

4. Set a Timeout

[Link](() => {
alert('This alert appears after 2 seconds');
}, 2000);

 JavaScript – Errors and Exceptions


1. Syntax Errors
o Definition: Syntax errors occur when the JavaScript engine encounters code that violates the
language syntax rules.
o Example: Missing semicolon, unclosed brackets, or using reserved keywords incorrectly.
2. Runtime Errors
o Definition: Runtime errors (or exceptions) occur during the execution of a program when
unexpected conditions are encountered.
o Example: Trying to access a property of null or undefined, division by zero, or calling a
function that doesn't exist.
3. Logical Errors
o Definition: Logical errors occur when the code executes without throwing any syntax or
runtime errors but produces incorrect results due to flawed logic.
o Example: Incorrect algorithm implementation, incorrect conditions in control structures, or
incorrect variable assignments.
4. The try...catch...finally Statement
o Usage: Used for error handling in JavaScript to catch and handle exceptions gracefully.

Example:

try {
// Code that may throw an error
throw new Error('Something went wrong');
} catch (error) {
// Handle the error
[Link]([Link]);
} finally {
// Execute cleanup code regardless of errors
[Link]('Cleanup code');
}

5. The throw Statement


o Usage: Used to manually throw custom errors or exceptions in JavaScript.

Example:

function divide(x, y) {
if (y === 0) {
throw new Error('Division by zero');
}
return x / y;
}

try {
[Link](divide(10, 0));
} catch (error) {
[Link]([Link]);
}

6. The onerror() Method


o Usage: Global error handling method that can be used to catch unhandled errors and
exceptions in JavaScript.

Example:

[Link] = function(message, url, line, column, error) {


[Link](`Error: ${message} at ${url}:${line}:${column}`);
// Additional error handling logic
};

 JavaScript – Form Validation


Basic Form Validation
Form validation in JavaScript ensures that user input meets specified criteria before submitting data to a
server. Here's a breakdown:

1. HTML Form

<form onsubmit="return validateForm()">


<input type="text" id="name" placeholder="Name" required>
<input type="email" id="email" placeholder="Email" required>
<button type="submit">Submit</button>
</form>

2. JavaScript Function validateForm()


o Purpose: Validates the form inputs (name and email).
o Returns: true if validation passes, allowing form submission; otherwise, displays alerts and
returns false.

<script>
function validateForm() {
let name = [Link]('name').value;
let email = [Link]('email').value;

// Check if name or email fields are empty


if (name === '' || email === '') {
alert('Please fill in all fields');
return false;
}

// Validate email format using a regular expression


if (!validateEmail(email)) {
alert('Invalid email format');
return false;
}

return true; // Form submission allowed


}

function validateEmail(email) {
// Regular expression for basic email validation
let re = /\S+@\S+\.\S+/;
return [Link](email);
}
</script>

Explanation:

 HTML Form:
o The form includes two input fields (name and email) and a submit button.
o required attribute ensures these fields cannot be empty.
 JavaScript Function validateForm():
o Fetching Input: Retrieves values of name and email fields from the form.
o Empty Check: Ensures both fields are filled; if not, alerts user and prevents form
submission.
o Email Validation: Utilizes validateEmail() function to check if the email format is valid
using a regular expression.
o Return Values: Returns true if all checks pass, allowing the form to be submitted.
Otherwise, alerts user and returns false.
 Function validateEmail(email):
o Purpose: Checks if the provided email matches the basic format using a regular expression
(/\S+@\S+\.\S+/).
o Return Value: Returns true if the email format is valid; otherwise, returns false.

 JavaScript – Animation
 Manual Animation
Manual animation involves changing CSS properties over time using JavaScript functions like
setInterval() or requestAnimationFrame().

Example:

let element = [Link]('animatedElement');


let position = 0;

function moveElement() {
position += 1;
[Link] = position + 'px';

if (position >= 200) {


clearInterval(animation);
}
}

let animation = setInterval(moveElement, 10);

In this example, moveElement() is called every 10 milliseconds to incrementally move an


element (#animatedElement) to the right until it reaches a position of 200 pixels.

 Automated Animation

Automated animation utilizes CSS transitions or libraries like GreenSock (GSAP) for creating
smooth and advanced animations.

Example using CSS Transitions:

<style>
.box {
width: 100px;
height: 100px;
background-color: red;
transition: transform 1s ease-in-out;
}

.box:hover {
transform: scale(1.5);
}
</style>

<div class="box"></div>

Here, the .box element scales to 1.5 times its size smoothly over 1 second when hovered over,
due to the CSS transition property.

 Rollover with Mouse Events

Rollover effects are commonly used to change an element's appearance when the mouse interacts
with it, using JavaScript events like mouseover and mouseout.

Example:

<img src="[Link]" onmouseover="[Link]='[Link]'"


onmouseout="[Link]='[Link]'">

In this example, when the mouse moves over the <img> element ([Link]), it changes to rollover-
[Link]. When the mouse moves out, it reverts to [Link].

 JavaScript – Multimedia
JavaScript multimedia refers to the use of JavaScript programming language to interact with and control
multimedia elements such as audio, video, and images within web pages. This capability enables
developers to create dynamic and interactive multimedia experiences directly within the browser
environment.

 Checking for Plug-Ins


JavaScript allows detection of browser plug-ins like Flash or PDF viewers using the [Link]
object. This object provides information about the plugins installed in the browser environment.

Example:

let hasFlash = [Link]('Shockwave Flash') !== null;


if (hasFlash) {
[Link]('Flash plug-in detected.');
} else {
[Link]('Flash plug-in not detected.');
}

In the example above:

 [Link]('Shockwave Flash') checks if the Shockwave Flash plug-in is


present.
 If namedItem('Shockwave Flash') returns a non-null value, it indicates that the Flash plug-in is
installed and available.

 Controlling Multimedia
JavaScript provides methods to manipulate multimedia elements such as audio and video directly in
the browser environment. This enables dynamic control over playback, pause, and seeking of
multimedia content.

Example:

let video = [Link]('myVideo');

function playVideo() {
[Link]();
}

function pauseVideo() {
[Link]();
}

function seekVideo(seconds) {
[Link] += seconds;
}

In the example above:

 [Link]('myVideo') retrieves the video element with the ID myVideo.


 play() method starts playing the video.
 pause() method pauses the video.
 currentTime property is used to seek to a specific time in the video.

 Javascript - Debugging

JavaScript debugging is a critical aspect of web development, ensuring that applications run
smoothly and errors are caught and resolved effectively. Here’s a comprehensive overview of
debugging JavaScript, including handling errors in different browsers, displaying custom error
notifications, debugging scripts, and useful tips for developers.

 Error Messages in Different Browsers

JavaScript code may behave differently across various browsers due to differences in
implementation and compatibility. Here’s how to handle and debug errors in different browsers:

 Using Developer Tools:


o Chrome: Access the Developer Tools by pressing F12 or right-clicking on the
page and selecting "Inspect". Errors are displayed in the Console tab.
o Firefox: Similarly, open the Developer Tools using F12 or right-clicking and
selecting "Inspect Element". Navigate to the Console tab for error messages.
o Internet Explorer (IE): Press F12 to open Developer Tools. Errors are shown in
the Console tab.
 Browser-Specific Error Handling:
o Conditional Checks: Detect the browser type using [Link] and
conditionally handle errors or features based on browser capabilities.
o Polyfills: Use polyfills to provide missing functionalities in older browsers that do
not support modern JavaScript features.
 Error Notifications

Displaying meaningful error notifications to users enhances user experience and helps in identifying
issues quickly:

 Using try...catch Blocks:

try {
// Code that may throw an error
} catch (error) {
// Handle the error
[Link]('An error occurred:', [Link]);
// Display user-friendly error message
alert('An unexpected error occurred. Please try again later.');
}

 Custom Error Handling Functions: Implement functions to display error messages in a


user-friendly format, avoiding technical details that users may not understand.

 How to Debug a Script

Debugging JavaScript involves using tools and techniques to identify and fix errors in code:

 Using Browser Developer Tools:


o Console Logging: Output debug messages using [Link]() or [Link]() to
track variable values and execution flow.
o Setting Breakpoints: Place breakpoints in the code using the Sources tab to pause
execution and inspect variables and states.
o Step-by-Step Execution: Step through code execution line by line to trace bugs and
logic errors.

 Image Map
An image map in HTML allows you to define clickable regions on an image, each associated with a
specific action or link. This is achieved using the <map> element along with <area> elements to
define the clickable areas.

Example:

<img src="[Link]" usemap="#planetmap">

<map name="planetmap">
<area shape="rect" coords="0,0,82,126" href="[Link]" alt="Sun">
<area shape="circle" coords="90,58,3" href="[Link]" alt="Mercury">
<area shape="circle" coords="124,58,8" href="[Link]" alt="Venus">
</map>

Explanation:

1. <img> Element:
o The <img> tag displays the image ([Link]) on the web page.
o The usemap attribute specifies the name of the image map (#planetmap) to use for
defining clickable areas.
2. <map> Element:
o
The <map> tag defines the image map with the name attribute set to "planetmap".
o
Inside <map>, multiple <area> tags define different clickable areas (<area>
elements).
3. <area> Elements:
o Rectangular Area: <area shape="rect" coords="0,0,82,126" href="[Link]"
alt="Sun">
 Defines a rectangular clickable area (shape="rect") with coordinates
(coords="0,0,82,126").
 href="[Link]" specifies the URL to navigate when this area is clicked.
 alt="Sun" provides alternative text for accessibility.
o Circular Areas:
 <area shape="circle" coords="90,58,3" href="[Link]" alt="Mercury">
 <area shape="circle" coords="124,58,8" href="[Link]" alt="Venus">
 These define circular clickable areas (shape="circle") with specified
coordinates (coords="x,y,radius").
 href attributes specify the URLs to navigate to when each area is clicked.
 alt attributes provide alternative text for accessibility purposes.

How It Works:

 When a user clicks within the defined areas on the image ([Link]), the browser navigates
to the specified URLs ([Link], [Link], [Link]).
 The coords attribute specifies the shape and position of each clickable area relative to the
image.
 This technique is useful for creating interactive images where different parts of the image
lead to different destinations or actions.

Using image maps can enhance user interaction and navigation on websites, especially when dealing
with complex images that represent clickable regions or hotspots. It's important to ensure that
coordinates and links are correctly set to provide a smooth user experience.

 JavaScript – Browsers
 Navigator Properties
The navigator object in JavaScript contains information about the web browser and the operating system.
It allows scripts to query and interact with the browser's properties and capabilities. The navigator object
is part of the window object and can be accessed using [Link].

 Overview of the navigator Object


 Properties

Property Description Example


Returns the code name of
[Link] the browser (e.g., [Link]([Link]);
"Mozilla")
Returns the name of the
[Link] [Link]([Link]);
browser (e.g., "Netscape")
Returns the version
[Link] information of the [Link]([Link]);
browser
Returns the user agent
[Link] [Link]([Link]);
string for the browser
Property Description Example
Returns the platform the
[Link] browser is running on [Link]([Link]);
(e.g., "Win32")
Returns a boolean
indicating whether
[Link] [Link]([Link]);
cookies are enabled in the
browser
Returns the language of
[Link] the browser (e.g., "en- [Link]([Link]);
US")
Returns a boolean
[Link] indicating whether the [Link]([Link]);
browser is online
Returns a Geolocation
object for accessing the [Link](position =>
[Link]
device's geographical [Link](position));
position
Returns a boolean
[Link]() indicating whether Java is [Link]([Link]());
enabled in the browser
Returns a PluginArray
[Link] object listing the [Link]([Link]);
browser's plugins
Returns a
MimeTypeArray object
[Link] [Link]([Link]);
listing the browser's
MIME types

 Methods

Method Description Example


Returns a boolean indicating
[Link]() whether Java is enabled in the [Link]([Link]());
browser
Sends a small amount of data to a [Link]('/log',
[Link]()
web server asynchronously [Link]({event: 'test'}));
Returns a promise that resolves
[Link]().then(battery =>
[Link]() with a BatteryManager object
[Link]([Link]));
providing battery status

Example

1. Detecting Browser Information

[Link]("Browser CodeName: " + [Link]);


[Link]("Browser Name: " + [Link]);
[Link]("Browser Version: " + [Link]);
[Link]("User-Agent: " + [Link]);
[Link]("Platform: " + [Link]);
[Link]("Language: " + [Link]);
[Link]("Online: " + [Link]);
[Link]("Cookies Enabled: " + [Link]);

2. Checking if Cookies are Enabled

if ([Link]) {
[Link]('Cookies are enabled.');
} else {
[Link]('Cookies are disabled.');
}

3. Geolocation API

if ("geolocation" in navigator) {
[Link](position => {
[Link]('Latitude: ' + [Link]);
[Link]('Longitude: ' + [Link]);
});
} else {
[Link]('Geolocation is not supported by this browser.');
}

4. Sending Data with sendBeacon

[Link]('/log', [Link]({ event: 'pageView' }));

 Browser Detection
Browser detection in JavaScript involves checking the userAgent property to identify the browser
type and version for conditional rendering or feature detection.

Example:

if ([Link]("Firefox") != -1) {
[Link]('You are using Firefox.');
} else if ([Link]("Chrome") != -1) {
[Link]('You are using Chrome.');
} else {
[Link]('Browser detection not supported.');
}

 [Link]: Contains a string that identifies the browser and its version.
 indexOf("Firefox") != -1: Checks if the user agent string contains "Firefox", indicating the
use of Firefox browser.
 indexOf("Chrome") != -1: Checks if the user agent string contains "Chrome", indicating the
use of Chrome browser.
 If neither condition matches, it logs that browser detection is not supported, which might
occur in less common or custom browsers.

 JavaScript – History Object


The history object in JavaScript provides an interface for manipulating the browser session history,
allowing you to move forward and backward through the user's navigation history, as well as add or
modify history entries.

 Overview of the history Object

 Properties

Property Description Example

[Link] Returns the number of entries in the history stack [Link]([Link]);

[Link] Returns the current state object at the top of the history stack [Link]([Link]);

 Methods

Method Description Example

Loads the previous URL in the history


[Link]() [Link]();
list

[Link]() Loads the next URL in the history list [Link]();

Loads a specific URL from the history


[Link](n) [Link](-1); // Go back one page
list, identified by its relative position

[Link](state, title, Adds a new entry to the history stack [Link]({page: 1}, "title 1",
url) without reloading the page "?page=1");

[Link](state, Modifies the current history entry [Link]({page: 2}, "title


title, url) without reloading the page 2", "?page=2");

Example

Navigating Through History

// Go back one page in history


[Link]();

// Go forward one page in history


[Link]();

// Go two pages back in history


[Link](-2);

// Go three pages forward in history


[Link](3);

Adding and Modifying History Entries

// Add a new history entry


[Link]({ page: 1 }, "title 1", "?page=1");
// Replace the current history entry
[Link]({ page: 2 }, "title 2", "?page=2");

// Check the current state object


[Link]([Link]); // { page: 2 }

 Using pushState and replaceState

 state is a JavaScript object that is associated with the new history entry. This can be anything that
can be serialized.
 title is a string containing the title to be displayed in the browser's title bar. However, most
browsers currently ignore this parameter.
 url is an optional string that should be an absolute or relative URL. The URL must be of the same
origin as the current URL.

You might also like