Javascript Engine
Javascript Engine
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:
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.
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.
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:
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.
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.
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.
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
reduce(function, initial) It executes a provided function for each value from left to right and reduces the array to a
single value.
slice() It returns a new array containing the copy of the part of the given array.
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:
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:
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:
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:
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:
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:
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.
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:
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:
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).
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.
Use Cases:
I. Iterating over object properties (keys).
II. Useful for tasks like serialization, deep cloning, or dynamic property access.
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.
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.
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:
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:
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: