Javascript
Javascript
What is JavaScript?
Why JavaScript?
1. Popularity:
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:
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.
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:
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:
User Notifications:
JavaScript can create dynamic pop-ups for user notifications on web pages.
Presentations:
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:
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.
Data Visualization:
Cloud Computing:
JavaScript is used in serverless computing platforms like Cloudflare and AWS Lambda.
Enables writing and deploying functions on the cloud.
JavaScript – Syntax
<!DOCTYPE html>
<html>
<head>
<title>My First JavaScript</title>
</head>
<body>
<h1>Hello, World!</h1>
<script>
[Link]('Hello, World!');
</script>
</body>
</html>
JavaScript ignores extra whitespace and line breaks, making it flexible for formatting:
let x = 5;
let y = 6;
let z = x + y;
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
SComments are used to explain code and are ignored by the interpreter.
/* This is a
multi-line comment */
let y = 10;
JavaScript – Enabling
B. JavaScript in Firefox
C. JavaScript in Chrome
D. JavaScript in Opera
JavaScript – Placement
Example
<!DOCTYPE html>
<html>
<head>
<script>
[Link]("This script is in the head section.");
</script>
</head>
<body>
<h1>JavaScript in Head</h1>
</body>
</html>
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>
Example
<!DOCTYPE html>
<html>
<head>
<title>External JavaScript</title>
<script src="[Link]"></script>
</head>
<body>
<h1>External JavaScript</h1>
</body>
</html>
Contents of [Link]:
Javascript – output
1. [Link]()
[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:
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]()
[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
E.g.
const z = 15;
[Link](z); // 15
z = 20; // TypeError: Assignment to constant variable.
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.
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.
if (true) {
let b = 20;
[Link](b); // 20
}
[Link](b); // ReferenceError: b is not defined
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
Reserved words are predefined by JavaScript and cannot be used as variable names:
JavaScript Datatypes
JavaScript supports several datatypes:
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.
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.
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.
Example:
5. Assignment Operators
Assignment operators assign values to variables.
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
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)
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'
9. String Operators
Example
let str1 = 'Hello';
let str2 = 'World';
[Link](str1 + ' ' + str2); // 'Hello World'
JavaScript – If-Else
A. if Statement
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:
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:
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:
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");
}
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++;
}
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);
The for loop is used when you know beforehand how many times you want to execute a statement or
a block of statements.
Syntax:
Example:
Syntax:
let person = {
name: 'John',
age: 30,
city: 'New York'
};
The break statement exits the loop immediately, regardless of the loop’s condition.
Example:
The continue statement skips the current iteration and proceeds to the next iteration of the loop.
Example:
Labels can be used to control the flow of nested loops when using break and continue.
Example:
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:
// code to be executed
Example:
function greet(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:
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!
Example:
function add(a, b) {
return a + b;
}
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');
}
Function() Constructor
Functions can also be created using the Function constructor, which takes the parameter names and
function body as strings.
Syntax:
Example:
Function Literals
Function literals are anonymous functions defined without a name. They are typically assigned to a
variable.
Syntax:
Example:
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.
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.
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:
//In this example, an alert box will be displayed when the button is clicked.
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:
//In this example, an alert box will be displayed when the form is submitted.
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:
//In this example, messages will be logged to the console when the mouse pointer moves over
and out of the image.
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
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
E. Mouse Events
F. Form Events
G. Media Events
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:
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.
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.
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;
}
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.
Cookie Attributes
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.
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.
// 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;
}
}
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).
// Storing data
[Link]("username", "JohnDoe");
// Retrieving data
let username = [Link]("username");
[Link](username); // Output: JohnDoe
// Removing data
[Link]("username");
localStorage
The localStorage object stores data with no expiration time. The data is available even after
the browser is closed and reopened.
// Storing data
[Link]("username", "JohnDoe");
// Retrieving data
let username = [Link]("username");
[Link](username); // Output: JohnDoe
// Removing data
[Link]("username");
Storage
4KB per cookie 5MB per origin 5MB per origin
Limit
Sent with every HTTP request Accessible only within the Accessible across tabs and
Accessibility
to the server current tab browser restarts
You can refresh the current page using the [Link]() method. This method reloads the resource
from the current URL.
Example:
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():
Using setInterval():
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:
Example
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.
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
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.
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.
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:
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.
Example:
Add a button element in your HTML and set its onclick attribute to call the printPage function.
Example:
<!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>
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.
Property Value
name Fiat
model 500
weight 850kg
color White
Method Description
Example:
JavaScript Objects
Objects are variables too, but they can contain multiple values. They are defined using object
literals or constructors.
const car = {
type: "Fiat",
model: "500",
color: "white"
};
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"
};
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
You can create objects using the new keyword and an object constructor.
Example:
Note: Using object literals is generally preferred for readability and performance.
Object Properties
Example:
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
1. Dot Notation:
2. Bracket Notation:
3. Expression:
Examples:
Example:
[Link] = "English";
o Deleting Properties
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.
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.
Example:
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName: function() {
return [Link] + " " + [Link];
}
};
In this example:
[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:
Example:
[Link] = function() {
return [Link] + " " + [Link];
};
You can also use JavaScript built-in methods within your object methods.
[Link] = function() {
return ([Link] + " " + [Link]).toUpperCase();
};
The JavaScript Number object has several properties that provide important information about
numeric values.
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.
B. Constructor
The constructor property returns the constructor function for a Number object.
Number Methods
The Number object has several built-in methods for performing operations on numbers.
Example
[Link] = function() {
return this % 2 === 0;
};
JavaScript – Boolean
Boolean Properties
The Boolean object has a few key properties, primarily constructor and prototype.
Boolean Methods
The Boolean object has several methods for operations on boolean values.
Example
let bool = true;
[Link] = function() {
return ![Link]();
};
JavaScript – String
A JavaScript string is zero or more characters written inside quotes.
String Properties
length Returns the length of the string. let str = "Hello"; [Link]([Link]);
String Methods
String object has many methods for manipulating strings.
split(separator, limit) Splits the string into an array of substrings. [Link](", ")
Example
Creating an Array
Arrays can be created using array literals or the new Array() constructor.
const cars = [
"Saab",
"Volvo",
"BMW"
];
Note: Using the array literal is generally preferred for simplicity and readability.
cars[0] = "Opel";
Arrays in JavaScript are objects with numbered indexes, making them different from regular objects,
which use named indexes.
JavaScript arrays can hold elements of various types, including other arrays, functions, and objects.
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
Array Loops
I. Using forEach():
A. Using push():
Recognizing Arrays
A. Using [Link]():
const myObj = {
name: "John",
age: 30,
cars: [
{name:"Ford", models:["Fiesta", "Focus", "Mustang"]},
{name:"BMW", models:["320", "X3", "X5"]},
{name:"Fiat", models:["500", "Panda"]}
]
};
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.
You can create a new date object using the Date constructor:
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.
getDay() Gets the day of the week (0-6). [Link]() 0-6 (0 is Sunday)
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
getYear() Gets the year minus 1900 (deprecated). [Link]() year minus 1900
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
setUTCHours(hours) Sets the UTC hour (0-23). [Link](18) Updated date object
setUTCMinutes(min
Sets the UTC minutes (0-59). [Link](30) Updated date object
utes)
Method Description Example Usage Example Output
setUTCSeconds(sec
Sets the UTC seconds (0-59). [Link](15) Updated date object
onds)
JavaScript – Math
The Math object in JavaScript provides properties and methods for mathematical constants and
functions.
Math Properties
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
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:
Examples
RegExp Properties
constructor Returns the function that created the RegExp object. [Link] function RegExp
RegExp Methods
Example Code
RegExp Properties
A. constructor: Specifies the function that creates an object's prototype.
RegExp Methods
exec(): Executes a search for a match in a string and returns the matched text along with
the position and input string.
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
Methods
Example
<script>
[Link]("demo").innerHTML = "Hello JavaScript!";
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script>
let newParagraph = [Link]("p");
[Link] = "This is a new paragraph.";
[Link]("div1").appendChild(newParagraph);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script>
[Link]("This is written directly to the document.");
</script>
</body>
</html>
Methods
Example Usage
1. Display an Alert
[Link]('[Link] '_blank');
[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);
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');
}
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]);
}
Example:
1. HTML Form
<script>
function validateForm() {
let name = [Link]('name').value;
let email = [Link]('email').value;
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:
function moveElement() {
position += 1;
[Link] = position + 'px';
Automated Animation
Automated animation utilizes CSS transitions or libraries like GreenSock (GSAP) for creating
smooth and advanced animations.
<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 effects are commonly used to change an element's appearance when the mouse interacts
with it, using JavaScript events like mouseover and mouseout.
Example:
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.
Example:
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:
function playVideo() {
[Link]();
}
function pauseVideo() {
[Link]();
}
function seekVideo(seconds) {
[Link] += seconds;
}
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.
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:
Displaying meaningful error notifications to users enhances user experience and helps in identifying
issues quickly:
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.');
}
Debugging JavaScript involves using tools and techniques to identify and fix errors in code:
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:
<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].
Methods
Example
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.');
}
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.
Properties
[Link] Returns the current state object at the top of the history stack [Link]([Link]);
Methods
[Link](state, title, Adds a new entry to the history stack [Link]({page: 1}, "title 1",
url) without reloading the page "?page=1");
Example
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.