0% found this document useful (0 votes)
23 views

Javascript Engine

Uploaded by

Aditya Yadav
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Javascript Engine

Uploaded by

Aditya Yadav
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

Introduction

JavaScript is one of the most versatile as well as the most used programming language in the world. It is used to make web
applications dynamic and interactive. JavaScript runs on JavaScript engines like V8 engine for chromium based browsers, Spider-
Monkey for Mozilla Firefox etc. It is based on scripting standards called ECMAScript. Currently JavaScript runs on ES14, the 14 th
and the latest version of ECMAScript. Some important points about JavaScript:

 Only language that can run natively on browsers


 Lightweight.
 Cross-Platform.
 Single-Threaded in nature.

JavaScript Engine:
As discussed earlier, JavaScript runs on JavaScript Engine. A JavaScript Engine is a software component that executes JavaScript
code. JavaScript Engines are mostly developed by browser vendors, most major browsers have their own JavaScript engine, For
example V8 engine for chromium based browsers, Spider-Monkey was developed by Mozilla for their browser Firefox,
JavaScriptCore also known as Nitro, is used by Apple for their browser Safari etc.

Single Threaded Nature of JavaScript:


JavaScript has one critical feature, that it is single threaded in nature. This means that it can only execute one task or statement at a
time. The program is executed sequentially line by line and each task has to be completed before the next task starts. Languages
like Java and Python are multi threaded in nature and are able to execute multiple tasks at the same time. Threads are lightweight
processes and each thread have their own call stack, for JavaScript this means that it only has a single call stack, leading to its
synchronous nature, something that will be discussed later in this section.
Variables & Datatypes
Just like most of the programming languages, Variables in JavaScript are also used to store values of different types and are the
building blocks for development of web applications. Something special about variables is that you can use them to contain just
about anything, not only strings, numbers but also complex data such as HTML elements as well as entire functions. Variables
can be Declared and initialized at the same time.

Scope of a Variable:

The term SCOPE refers to the current context of execution in which the variable is being accessed or is visible: There are 3 types
of scopes in which a varible can exist:

 Global-Scope: In JavaScript, Global scope is the widest of them all, Variables declared usinng the global scope can be
accessed anywhere in the file. Variables declared in global scope are defined outside of any function or code blocks. Any
function or code block with the program can access a global variable.

 Block-Scoped: A block is created using curly braces {}, any varibles declared inside that block are block-scoped variables,
these variables cannot be accessed outside this block of code, Example: If block, for-loop block.

 Function-Scope: When we declare a function, it creates a scope and any variable created inside that function is function-
scoped, that variable can be accessed anywhere in the function. Even the variables created inside a block inside the
function can be accessed outside that block.

Declaration of Variables:
There are mainly 3 ways that you can declare a variable in JavaScript by using let, const or var. Var used to be the only way of
declaration until let and const were introduced much later in ES6.

 LET: Let keyword lets us create a global scoped and block scoped varibles. These variables are re-assignable, meaning they
can be assigned with a new value anytime. it is optional to initialize (assigning them a value) these variables during there
declaration.

 CONST: Const keyword allows us to create a variable which is block or global scoped (depending on where it is declared).
The key characteristic of variables decaled using const keyword is that the value of these variables cannot be changed once
they are initialized. It is necessary to initialize these variables during declaration.
 VAR: Var is the oldest way to declare a variable, variables created using var keyword are function scoped. Var variables go
through a process called hoisting, something that will be discussed later in this module.

Datatypes:
The term Datatype refer to the type of value that being stored in a variable. In JavaScript, one doesn’t need to explicitly provide
a datatype of a variable during declaration like other languages such as java, c++ etc. JavaScript is able to detect the datatype of
a variable on it’s own. On a higher level, datatypes can be divided into 2 categories, Primitve Datatypes and Non-Primitive
Datatypes.

Primitive Datatypes:

A Datatype is considered a primitive datatype if it is not an object, meaning it doesn’t have any functions or properties of it’s
own. Primitive datatypes are immutable which means that there values can’t be altered, if altered the variable is assigned a new
space in the memory stack and the old value still exists in the original space. JavaScript does not provide any methods to mutate
these values. Here are some primitive datatypes:

 Number: Any type of numeric value decimal or non-decimal is considered a number in JavaScript.

 String: Character or Set of Characters are categorized as strings in JavaScript.

 Boolean: In JavaScript Boolean is a logical datatype which can hold only 2 values true or false.

 BigInt: BigInt data type can represent numbers greater than 252-1 which helps to perform operations on large numbers. The
numbers is specified by writing ‘n’ at the end of the value.

 Null: This datatype can only hold one value which is null. A Null value generally points towards a non-existant or invalid
address or object. In JavaScript Null is considered a primitive datatype because of its primitive behaviour, but when we use
the typeOf method on null, it returns object.

 Undefined: Undefined is automatically assigned to variables which have been declaed but whose values are not initiallized
yet.
Non-Primitive Datatypes:

The data types that are derived from primitive data types of the JavaScript language are known as non-primitive data types. It is
also known as derived or reference data types. Common non-primitive types are Object, Arrays, RegExp. All of the are
considered Objects. Let’s discuss some of these in detail:

 Objects:

In JavaScript, An object is entity with a state and behaviour i.e. Properties and Methods. JavaScript is considered an object-
based-language since technically Everything in JavaScript is an Object. Unlike languages like java and c++, JavaScript is template
based not class based, Here we dont create a class to create an object, we create an object directly. In Objects the data is stored
in the form of key-value pairs like the example shown below:

There are several ways to create an object, some of them being:

1. By Using the literal notation to define a JavaScript object.


2. By using the Object Constructor.

3. By using Object.create() method.

 Arrays:

An array is a data structure which is used to store more than one element under a single name. In JavaScript arrays aren’t
primitive in nature, instead arrays follow the following characteristics:

 JavaScript arrays are resizable and can contain a mix of different data types.
 JavaScrpt arrays are not associative and must be accessed using non-negative integers as indexes.
 JavaScript arrays are zero-indexed. The first element of an array is at index 0, the second is at index 1, and so on and the
last element is at the value of the array’s length property minus 1.

An array can be created using 3 methods:

1. By using Array literals.


2. By using Array constructor. The constructor can also take in values so that the array can be initialized at the time of
creation.

The Array Object comes with many built-in methods that can help us perform many basic operations on the array, Some of the
methods will be discussed in the table below:
Methods Description

concat() It returns a new array object that contains two or more merged arrays.

copyWithin() It copies the part of the given array with its own elements and returns the modified array.

entries() It creates an iterator object and a loop that iterates over each key/value pair.

every() It determines whether all the elements of an array are satisfying the provided function
conditions.

flat() It creates a new array carrying sub-array elements concatenated recursively till the specified
depth.

flatmap() It maps all array elements via mapping function, then flattens the result into a new array.

fill() It fills elements into an array with static values.

from() It creates a new array carrying the exact copy of another array element.

filter() It returns the new array containing the elements that pass the provided function conditions.

find() It returns the value of the first element in the given array that satisfies the specified
condition.

findIndex() It returns the index value of the first element in the given array that satisfies the specified
condition.

forEach() It invokes the provided function once for each element of an array.

includes() It checks whether the given array contains the specified element.

indexOf() It searches the specified element in the given array and returns the index of the first match.

join() It joins the elements of an array as a string.

lastIndexOf() It searches the specified element in the given array and returns the index of the last match.

map() It calls the specified function for every array element and returns the new array

push() It adds one or more elements to the end of an array.


pop() It removes and returns the last element of an array.

reverse() It reverses the elements of given array.

reduce(function, initial) It executes a provided function for each value from left to right and reduces the array to a
single value.

shift() It removes and returns the first element of an array.

slice() It returns a new array containing the copy of the part of the given array.

sort() It returns the element of the given array in a sorted order.

toString() It converts the elements of a specified array into string form, without affecting the original
array.

unshift() It adds one or more elements in the beginning of the given array.

values() It creates a new iterator object carrying values for each index in the array.
Operators in JavaScript
JavaScript operators are symbols used to perform specific mathematical, comparison, assignment, and logical computations on
operands. They are fundamental elements in JavaScript programming, allowing developers to manipulate data and control
program flow efficiently. There are various forms of operators that are supported by JavaScript. following are the categories of
operators supported by JavaScript:

 Arithmetic Operators:

Generally used on numerical values, Arithmetic Operators are used to perform arithmetic computations on the numerical
operands and then return a singular numerical value. Below are some of the arithmetic operators commonly used in js:

1. Addition (+) : Performs addition on two operands.


2. Subtraction(-) : Performs subtraction between two operands.
3. Multiplication(*) : Performs multiplication between two operands.
4. Division(/) : Performs division between two operands.
5. Modulus(%) : Gives us the remainder between two operands.
6. Exponentiation(**) : Raise the Left operator to the power of the right operator
7. Increment(++) : there are 2 types of increment operators, both increase the operands value by 1 but in different ways,
i. a++ : Returns the operand and increases the operands value by 1 after the line execution.
ii. ++a : increases the value of the operand by 1 and then returns it.
 Comparison Operators:

A comparison operator compares its operands and returns a logical value based on whether the comparison is true. The
operands can be numerical, string, logical, or object values. Strings are compared based on standard lexicographical ordering,
using Unicode values. In most cases, if the two operands are not of the same type, JavaScript attempts to convert them to an
appropriate type for the comparison. This behavior generally results in comparing the operands numerically. The sole exceptions
to type conversion within comparisons involve the === and !== operators, which perform strict equality and inequality
comparisons. These operators do not attempt to convert the operands to compatible types before checking equality. Following
are some of the most used comparison operators:

1. Equal (=) : Returns true if the operands are equal.


2. Not equal (!=) : Returns true if the operands are not equal.
3. Strict equal (===) : Returns true if the operands are equal and of of the same type.
4. Strict not equal (!==) : Returns true if the operands are of the same type but not equal or are of different type.
5. Greater than (>) : Returns true if the left operand is greater than the right operand.
6. Greater than or equal (>=) : Returns true if the operand is greater than or equal to the right operand.
7. Less than (<) : Returns true if the left operand is greater than or equal to the right operand.
8. Less than or equal (<=) Returns true if the left operand is less than or equal to the right operand.

 Logical Operations:

Logical operators are typically used with Boolean (logical) values; when they are, they return a Boolean value. However, the &&
and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean
values, they may return a non-Boolean value. Following are the logical operators that used in JavaScript:

1. Logical AND ( expression1 && expression2) : Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus,
when used with Boolean values, && returns true if both operands are true; otherwise, returns false.
2. Logical OR (||) : Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean
values, || returns true if either operand is true; if both are false, returns false.
3. Logical NOT (!) : Returns false if its single operand that can be converted to true; otherwise, returns true.
 Assignment Operators:

NAME SHORTHAND OPERATOR MEANING

Assignment a=b a=b


Addition Assignment a+=b a= a+b
Subtraction Assignment a-=b a=a-b
Multiplication Assignment a*=b a=a*b
Division Assignment a/=b a=a/b
Remainder Assignment a%=b a=a%b
Exponentiation Assignment a**=b a=a**b
Left Shift Assignment x
Right Shift Assignment
Conditional Statements
Conditional statements, also known as decision-making statements, play a crucial role in programming. They allow your program
to perform different actions based on whether a certain condition is true or false. Think of them as the traffic signals of your
code—they guide the execution path based on specific rules. Below are some key points about conditional statements :

1. Purpose : Conditional statements help you create dynamic, responsive programs by allowing you to choose different paths
based on varying conditions.
2. Types : There are several types of conditional statements, each serving a specific purpose:

a) If-else Statements:

The if…else statement is one of the most common conditional structures in JavaScript. It allows you to execute different blocks
of code depending on whether a condition evaluates to true or false.

BASIC SYNTAX:

Here’s what each part of the syntax means:

 The keyword if followed by parentheses.


 A condition inside the parentheses (e.g., “Is this value bigger than that value?”).
 The condition uses comparison operators (e.g., >, <, ===) and returns either true or false.
 A set of curly braces {} containing the code to run if the condition is true.
 The keyword else.
 Another set of curly braces {} containing the code to run if the condition is false.
Example:
Remember that you can omit the else part if you only want to execute code when the condition is true.
If-else If Statements:

Allows multiple conditions to be checked sequentially. The syntax is illustrated below:

b) Switch Statements:

The switch statement evaluates an expression, matching the expression's value against a series of case clauses, and executes
statements after the first case clause with a matching value, until a break statement is encountered. The default clause of a
switch statement will be jumped to if no case matches the expression's value. The switch case statement provides an alternative
way to handle multiple conditions. It’s especially useful when you have a single expression that you want to compare against
different values.

BASIC SYNTAX:

Here’s what each part of the syntax means:

 The keyword switch followed by parentheses containing an expression to evaluate.


 Multiple case statements, each representing a specific value of the expression.
 Code blocks associated with each case.
 The break statement to exit the switch block after executing the relevant case.
 An optional default case that runs when none of the specified cases match.
Example:

c) Ternary Operators (Conditional Operators):

 The ternary operator is a concise way to express a conditional (if-else) statement in many programming languages.
 It is represented by the ? symbol and is sometimes called the ternary operator because it takes three operands.
 The three parts of the ternary operator are:

 Condition: A boolean expression that evaluates to either true or false.


 True Value: The value to be returned if the condition is true.
 False Value: The value to be returned if the condition is false.

 Syntax:

 Example:

If the expression evaluates to true, the trueValue is returned or executed.If the expression evaluates to false, the falseValue is
returned or evaluated. This behavior is called short-circuiting. Ternary operators allow you to write simple conditionals in a
compact form. whether you use if...else statements or ternary operators, both serve the purpose of making decisions based on
conditions.
Loops & Iterations
Loops, also known as iterative statements, are essential when we need to execute a block of code repetitively. They allow us to
perform specific tasks efficiently by reducing hours of manual work to mere seconds. In this article, we’ll cover the basics of
loops, different types, and best practices. On a higher level loops can be categorized in two categories:

1. Entry-Controlled loops: Entry-controlled loops are loop structures where the condition is evaluated before executing the
loop body. If the condition evaluates to true, the loop body is executed; otherwise, the loop terminates without executing
the loop body. Some famous example of entry controlled loop would the While loop and For-loop.

2. Exit-Controlled loops: Exit-controlled loops are loop structures where the loop’s condition is checked after the loop body
has executed. This means that the loop will always execute at least once, regardless of whether the condition is true or
false initially. An example of exit controlled loops would be do-while loops.

 For-Loop:
A for loop is a control flow statement that allows you to execute a block of code repeatedly based on a specified condition. It is
commonly used when you know how many times you want to execute a block of code. The main components required to use a
for loop are:

1. Initialization: This part of the loop is where you initialize a variable or set a starting value for a counter variable that
controls the loop. It typically occurs before the loop starts and is executed only once.

2. Condition: The condition is a Boolean expression that determines whether the loop should continue executing or not. If the
condition evaluates to true, the loop body is executed. If it evaluates to false, the loop terminates.

3. Increment (or Decrement): This part of the loop is responsible for updating the loop control variable after each iteration. It
typically occurs at the end of each iteration and is used to modify the loop control variable to eventually make the
condition false.

The syntax for-loop in JavaScript is:


Working of a For-loop:
Here’s a breakdown of how for-loop works :
a) Initialization: The loop control variable is initialized or assigned an initial value before the loop starts. This step typically
occurs once, at the beginning of the loop.
b) Condition Check: The loop condition is evaluated before each iteration of the loop. If the condition evaluates to true, the
loop body is executed. If it evaluates to false, the loop terminates, and the program continues with the next statement
following the loop.
c) Loop Body Execution: If the condition evaluates to true, the statements within the loop body are executed. This is where
you specify the actions you want to perform during each iteration of the loop.
d) Increment or Decrement: After executing the loop body, the loop control variable is updated based on the specified
increment or decrement operation.

Use cases:
Following are some use-cases of for loops :
I. Iterating over arrays, lists, or ranges of numbers.
II. Processing data elements sequentially.
III. Implementing algorithms that require a fixed number of iterations.

 While loop:
The while loop is a fundamental control flow structure (or loop statement) in programming. A while loop is an entry-controlled
loop that repeatedly executes a block of code as long as a specified condition remains true. Unlike the for loop, which is tailored
for iterating a fixed number of times, the while loop excels in scenarios where the number of iterations is uncertain or
dependent on dynamic conditions. A while loop is defined using the following syntax:

Working of a While loop:


The while loop works by repeatedly executing a block of code as long as the specified condition remains true. Let’s break down
how a while loop works step by step:
1. Condition Evaluation: The while loop begins by evaluating the specified condition. If the condition is true, the code block
inside the loop is executed. If the condition is false initially, the code block is skipped, and the loop terminates immediately
without executing any code inside.
2. Block Execution: If the condition evaluates to true, the code block inside the while loop is executed. This is where you
specify the actions you want to perform during each iteration of the loop.
3. Condition Re-evaluation: After executing the loop body, the condition is re-evaluated. If it remains true, the loop continues
to execute the code block. If it becomes false, the loop terminates.
Use Cases:
The while loop works by repeatedly executing a block of code as long as the specified condition remains true. Let’s break down
how a while loop works step by step:
I. Dynamic Iteration: When the number of iterations is uncertain or dependent on dynamic conditions.
II. Input Validation: Validating user inputs until a specific condition is met.
III. Reading Data: Reading data from a stream or file until the end of data is reached.

 Do-while loop:
A do-while loop is a control flow statement (or loop statement) commonly found in many programming languages. It is similar to
the while loop but with one crucial difference: the condition is evaluated after the execution of the loop’s body. This ensures
that the loop’s body is executed at least once, even if the condition is initially false. The basic syntax of the do-while loop is as
follows:

Working of a do-while loop:


The do-while loop is a control flow construct used in programming to execute a block of code repeatedly until a specified
condition becomes false. Here’s how the do-while loop works:
1. Initialization: The loop starts with the execution of the block of code inside the do statement. Unlike other loop types, the
do-while loop guarantees that the block of code will be executed at least once, regardless of the condition.
2. Condition Evaluation: After executing the block of code inside the do statement, the condition specified after the while
keyword is evaluated. This condition determines whether the loop should continue iterating or terminate. If the condition
evaluates to true, the loop continues; if it evaluates to false, the loop terminates.
3. Iterative Execution: If the condition evaluates to true, the loop body is executed again, and the process repeats.

Use Cases:
I. Ensuring initialization or setup code runs before checking the condition.
II. Reading data from a stream or file until the end of the data is reached.
III. Implementing menu-driven programs where the user interacts with options at least once.

 for...of loop:
The for...of loop is used to iterate over elements in an iterable object such as arrays. It allows you to process each value directly
without worrying about index management. The basic syntax for for...of loop is as follows:
In this syntax:
i. element represents the current value from the iterable.
ii. iterable is any object that has an iterable protocol (e.g., arrays, strings, maps, sets).

Working of a for...of loop:


The do-while loop is a control flow construct used in programming to execute a block of code repeatedly until a specified
condition becomes false. Here’s how the do-while loop works:
1. Iterating Over Elements: The for…of loop iterates over each element in the iterable object.
2. Direct Access: Inside the loop, you can directly access the current element using the iterable object.
3. No Need for Index: Unlike traditional for loops, you don’t need manage an index or track the length of the iterable.
4. Example:

Use Cases:
I. Iterating over arrays, strings, maps, sets and other iterable objects.
II. Simplifying code when you don’t need the index.

 for...in loop:
The for...in loop is specifically designed for iterating over the enumerable properties of an object. The basic syntax for for...of
loop is as follows:

In this syntax:
iii. Key represents the current property name (key) from the object.
iv. Object is the object whose properties you want to iterate over.

Working of a For…in loop:


1. Iterating Over Properties: The for...in loop iterates over each enumerable property (key) of the specified object.
2. Direct Access to Property Names: Inside the loop, you can directly access the current property name (key) using the key
variable.
3. No Guaranteed Order: The order of iteration is not guaranteed, and it may vary depending on the JavaScript engine.

Use Cases:
I. Iterating over object properties (keys).
II. Useful for tasks like serialization, deep cloning, or dynamic property access.

 Break & Continue:


Break and continue keywords in js give us more control over iteration operations in JavaScript, let’s discuss about them in detail:

1. Break:
The break statement is used to exit a loop prematurely. When encountered, it immediately terminates the loop and transfers
control to the statement following the loop. Here are the key points about the break statement:

Usage:
a) In a for, while, or do-while loop, the break statement can be used to exit the loop early.
b) It is commonly used to stop further iterations when a specific condition is met.

Example:
2. Continue:
The continue statement is used to skip the current iteration of a loop and move on to the next iteration. It allows you to bypass
specific code within the loop. Here are the key points about the continue statement:

Usage:
I. In a for, while, or do-while loop, the continue statement skips the remaining code within the current iteration and proceeds
to the next iteration.
II. It is useful for excluding certain values or conditions from processing.

Example:
Functions
Functions are one of the fundamental building blocks in JavaScript. A function in JavaScript is similar to a procedure—a set of
statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and
return an output where there is some obvious relationship between the input and the output. To use a function, you must
define it somewhere in the scope from which you wish to call it.

Defining Functions:
I. Function Declaration:

A function definition (also called a function declaration, or function statement) consists of the function keyword, followed by:
 The name of the function.
 A list of parameters to the function, enclosed in parentheses and separated by commas.
 The JavaScript statements that define the function, enclosed in curly braces, { /* … */ }.
Example:

The function square takes one parameter, called number. The function consists of one statement that says to return the
parameter of the function (that is, number) multiplied by itself. The return statement specifies the value returned by the
function, which is number * number. Parameters are essentially passed to functions by value — so if the code within the body of
a function assigns a completely new value to a parameter that was passed to the function, the change is not reflected globally or
in the code which called that function.

Some Things to note:


1. When you pass an object as a parameter, if the function changes the object's properties, that change is visible outside the
function, as shown in the following example:
2. When you pass an array as a parameter, if the function changes any of the array's values, that change is visible outside the
function, as shown in the following example:

II. Function Expression:

While the function declaration above is syntactically a statement, functions can also be created by a function expression. Such a
function can be anonymous, it does not have to have a name. For example, the function square could have been defined as:

Calling Function:
Defining a function does not execute it. Defining it names the function and specifies what to do when the function is called.
Calling the function actually performs the specified actions with the indicated parameters. For example, if you define the
function square, you could call it as follows: square(5) . The preceding statement calls the function with an argument of 5. The
function executes its statements and returns the value 25.

Functions must be in scope when they are called, but the function declaration can be hoisted (appear below the call in the code).
The scope of a function declaration is the function in which it is declared (or the entire program, if it is declared at the top level).
The arguments of a function are not limited to strings and numbers. You can pass whole objects to a function.

A Function is also able to call itself, let’s take a look at a classic example of a recursive function:
Function Hoisting:

Hoisting is JavaScript’s behavior of moving variable and function declarations to the top of their scope before code execution.
However, hoisting does not apply to function expressions and arrow functions. Consider to the example below to understand
the concept of function hoisting:

In the above example even though the function square() was called before it was even declared and defined, the program still
worked just fine due to the concept of function hoisting.

Function Parameters:
In JavaScript, parameters are the names listed in the function definition. Parameters allow you to customize the behavior of your
function by accepting input values. There are two special kinds of parameter syntax: default parameters and rest parameters.
1. Rest Parameters: Rest parameters allow you to pass an arbitrary number of arguments to a function. They are represented
by the ... syntax and are useful when you don’t know how many arguments you’ll receive. Here’s an example of there use:

2. Default Parameters: In JavaScript, parameters of functions default to undefined. However, in some situations it might be
useful to set a different default value. This is exactly what default parameters do. Default parameters allow you to set
default values for function parameters. If no value is provided, the default value is used. Default parameters were
introduced in ES6. Here’s an example of there use:
Function Parameters:
Arrow functions provide an alternative syntax for writing function expressions. They allow you to create shorter and more
elegant functions. The name “arrow function” comes from the use of the arrow (=>) symbol. These were introduced in ES6 and
have become widely used due to their simplicity and readability. Mentioned below are some key points about arrow functions:
 Basic Syntax:

 Shorter Syntax: If the function body contains only one statement, you can omit the curly braces {} and the return keyword:

 No Binding of this: Arrow functions do not have their own this context. They inherit the this value from the surrounding
lexical scope. This behavior is different from regular functions, where this can vary based on how the function is called.

 When to use Arrow Functions: Arrow functions usually should be used when you need a concise function expression, You
need to avoid issues with this context and when you’re dealing with simple, single-expression functions.

Example of a simple arrow function:


Browser Object Model
The Browser Object Model (BOM) is a crucial part of JavaScript when it comes to web development. It provides a set of objects
that allow JavaScript code to interact with the web browser itself. Unlike the Document Object Model (DOM), which deals with
the structure and content of web pages, the BOM focuses on the browser window, frames, and other browser-specific
functionalities. The default object of browser is window means you can call all the functions of window by specifying window or
directly. For example:

The Browser object model consists of several different objects, let’s go through each one of them one by one:

 Window Object:

The primary object in the BOM is the window object. It represents the browser window and provides access to various browser-
related features. Some common methods and properties associated with the window object include:
1. alert(): Displays an alert dialog.
2. confirm(): Shows a modal dialog with a question.
3. prompt(): Prompts the user to input text.
4. setTimeout(): Sets a timer and executes a callback function once the timer expires.
5. setInterval(): Repeatedly executes a callback function with a fixed delay between each call.

 History Object:

The History object is part of the BOM and represents the user’s session history within a browser window or tab. It maintains an
array of visited URLs during the current browsing session. You can access the History object through the window.history
property. You can use it to navigate backward or forward through the user’s browsing history. Some common methods and
properties associated with the history object include:

1. length(): The length property returns the number of URLs in the session history. It indicates how many pages the user
has visited during their browsing session.forward(): Shows a modal dialog with a question.
2. forward(): The forward() method loads the next page in the session history. It has the same effect as clicking the
forward button in the browser. Note that this method won’t work if the next page doesn’t exist in the history list.
3. back(): The back() method loads the previous page in the session history. It simulates clicking the back button in the
browser. Similar to forward(), it won’t work if the previous page isn’t available in the history list.
4. go(distance): The go(distance) method allows navigation to a specific page in the history. A positive distance value
moves forward, while a negative value moves backward.
Example Usage:
 Using back() to go back one page:

 Using forward() to go forward one page:

 Using go to navigate n number of pages:

 Navigator Object:

The Navigator object is part of the Browser Object Model (BOM). It represents the state and identity of the user agent (i.e., the
web browser). You can use the Navigator object to query browser-related details. Common properties of navigator object are:

1. appCodeName(): Returns the browser code name (e.g., “Mozilla”). It’s a legacy property and not commonly used.
2. appName(): Returns the browser name (e.g., “Netscape” or “Microsoft Internet Explorer”). Also a legacy property.
3. appVersion(): Provides the browser version information (e.g., “5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36”).
4. cookieEnabled(): Returns true if browser cookies are enabled, otherwise false.
5. language(): Retrieves the browser language (e.g., “en-US” for English, United States).
6. onLine(): Returns true if the browser is online, otherwise false.
7. platform(): indicates the browser platform (e.g. “Win32” or “MacIntel”.
8. userAgent(): Provides the browser user-agent header, which includes information about the browser, operating system,
and rendering engine.

Example Usage:
 Check if cookies are enabled:

 Get browser language:

 Check online status:

 Retrieve user agent:

 Screen Object:

The Screen object is part of the Browser Object Model (BOM). It represents the user’s screen or monitor and provides details
related to display properties. You can access the Screen object through the window.screen property. Some common properties
of screen object are:

I. availHeight(): Returns the available height of the screen (excluding the Windows Taskbar). It represents the usable vertical
space for displaying content.
II. availWidth(): Returns the available width of the screen (excluding the Windows Taskbar). It indicates the usable horizontal
space for rendering content.
III. colorDepth(): Provides the bit depth of the color palette used for displaying images. Higher values indicate better color
representation.
IV. height(): Returns the total height of the screen (including any reserved areas like the Taskbar).
V. width(): Gives the total width of the screen (including any reserved areas).
VI. pixelDepth(): Specifies the color resolution in bits per pixel (bpp) for the screen. For example, a value of 24 bpp indicates 8
bits each for red, green, and blue channels.

Example Usage:
 Retrieve Screen Dimensions:

 Get color depth:

 Get total screen dimensions:

You might also like