You are on page 1of 71

Unit 4: The Basics of JavaScript

4.1 Overview of JavaScript


JavaScript is a lightweight, cross-platform, and interpreted compiled programming language
which is also known as the scripting language for webpages. Its syntax is based on the Java
and C languages — many structures from those languages apply to JavaScript as well.
JavaScript can be used for Client-side developments as well as Server-side developments.
Javascript is both imperative and declarative type of language. JavaScript contains a standard
library of objects, like Array, Date, and Math, and a core set of language elements
like operators, control structures, and statements.

● Client-side: It supplies objects to control a browser and its Document Object Model
(DOM). Like if client-side extensions allow an application to place elements on an HTML
form and respond to user events such as mouse clicks, form input, and page navigation.
● Server-side: It supplies objects relevant to running JavaScript on a server. Like if the
server-side extensions allow an application to communicate with a database, and provide
continuity of information from one invocation to another of the application, or perform file
manipulations on a server.
● Imperative language – imperative code focuses on writing an explicit sequence of
commands to describe how you want the computer to do things.
● Declarative programming – declarative code focuses on specifying the result of what
you want. Developers are more concerned with the answer that is received. It declares what
kind of results we want and leave programming language aside focusing on simply figuring
out how to produce them.

JavaScript can be added to your HTML file in two ways:


● Internal JS: We can add JavaScript directly to our HTML file by writing the code inside
the <script> tag. The <script> tag can either be placed inside the <head> or the <body> tag
according to the requirement.
● External JS: We can write JavaScript code in other file having an extension.js and then
link this file inside the <head> tag of the HTML file in which we want to add this code.
Syntax:
<script>
// JavaScript Code
</script>
Features of JavaScript:
Here are a few things that we can do with JavaScript:
● JavaScript was created in the first place for DOM manipulation. Earlier websites were
mostly static, after JS was created dynamic Web sites were made.
● Functions in JS are objects. They may have properties and methods just like another object.
They can be passed as arguments in other functions.
● Can handle date and time.
● Performs Form Validation although the forms are created using HTML.
● No compiler is needed.

Applications of JavaScript:
● Web Development: Adding interactivity and behavior to static sites
● Web Applications: With technology, browsers have improved to the extent that a language
was required to create robust web applications. When we explore a map in Google Maps
then we only need to click and drag the mouse. All detailed view is just a click away, and
this is possible only because of JavaScript. It uses Application Programming
Interfaces(APIs) that provide extra power to the code.
● Server Applications: With the help of Node.js, JavaScript made its way from client to
server and node.js is the most powerful on the server-side.
● Games: Not only in websites, but JavaScript also helps in creating games.
● Smartwatches: JavaScript is being used in all possible devices and applications. It
provides a library PebbleJS which is used in smartwatch applications. This framework
works for applications that require the internet for its functioning.
● Art: Artists and designers can create whatever they want using JavaScript to draw on
HTML 5 canvas.
● Machine Learning: This JavaScript ml5.js library can be used in web development by
using machine learning.
● Mobile Applications: The features and uses of JavaScript make it a powerful tool for
creating mobile applications.
Advantages of JavaScript
The merits of using JavaScript are −
● Less server interaction − You can validate user input before sending the page off to
the server. This saves server traffic, which means less load on your server.
● Immediate feedback to the visitors − They don't have to wait for a page reload to see
if they have forgotten to enter something.
● Increased interactivity − You can create interfaces that react when the user hovers
over them with a mouse or activates them via the keyboard.
● Richer interfaces − You can use JavaScript to include such items as drag-and-drop
components and sliders to give a Rich Interface to your site visitors.

Limitations of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It lacks the following
important features −
● Client-side JavaScript does not allow the reading or writing of files. This has been kept
for security reason.
● JavaScript cannot be used for networking applications because there is no such support
available.
● JavaScript doesn't have any multi-threading or multiprocessor capabilities.

Client-Side JavaScript
Client-side JavaScript is the most common form of the language. The script should be included
in or referenced by an HTML document for the code to be interpreted by the browser.
It means that a web page need not be a static HTML, but can include programs that interact
with the user, control the browser, and dynamically create HTML content.
The JavaScript client-side mechanism provides many advantages over traditional CGI server-
side scripts. For example, you might use JavaScript to check if the user has entered a valid e-
mail address in a form field.
The JavaScript code is executed when the user submits the form, and only if all the entries are
valid, they would be submitted to the Web Server.
JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and
other actions that the user initiates explicitly or implicitly.
• JavaScript ES6 (also known as ECMAScript 2015 or ECMAScript 6) is the newer
version of JavaScript that was introduced in 2015

• ECMAScript is the standard that JavaScript programming language uses

• ECMAScript provides the specification on how JavaScript programming language


should work.

4.2 The <script> tag


The <script> tag in HTML is used to define the client-side script.
The <script> tag contains the scripting statements, or it points to an external script file.
The JavaScript is mainly used in form validation, dynamic changes of content, image
manipulation, etc.
Syntax:
<script> Script Contents... </script>

Attributes of HTML script tag

Attribute Description

src It specifies the URL of an external script file.

type It specifies the media type of the script.

async It is a boolean value which specifies that the script is executed


asynchronously.
i.e., Specifies that the script is downloaded in parallel to parsing
the page, and executed as soon as it is available (before parsing
completes) (only for external scripts)

defer It is a boolean value which is used to indicate that script is


executed after document has been parsed.
i.e., Specifies that the script is downloaded in parallel to parsing
the page, and executed after the page has finished parsing (only
for external scripts)

The script tag can be used within <body> or <head> tag to embed the scripting code.
The browser loads all the scripts included in the <head> tag before loading and rendering
the <body> tag elements. So, always include JavaScript files/code in the <head> that are going
to be used while rendering the UI. All other scripts should be placed before the
ending </body> tag. This way, you can increase the page loading speed.
Example Program:
<html>
<body>
<script type="text/javascript">
document.write("JavaScript is a simple language for javatpoint learners");
</script>
</body>
</html>
Output:

Let's see the example to have script tag within HTML head tag.
<html>
<head>
<script type="text/javascript">
function msg(){
alert("Hello Javatpoint");
}
</script>
</head>
<body>
<p>Welcome to Javascript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
Output:

The script tag can be used to link external script file by src attribute. It must be used within the
<head> tag only. write JavaScript code in a separate file with .js extension and include it in a
web page using <script> tag and reference the file via src attribute.
Example Program:
message.js
function msg(){
alert("Hello Javatpoint");
}
Index.html
<html>
<head>
<script type="text/javascript" src="message.js"></script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body> </html>

4.3 Document Object Model (DOM)

The Document Object Model (DOM) is a programming interface for HTML (HyperText
Markup Language) and XML(Extensible markup language) documents. The Document
Object Model (DOM) is a platform and language-neutral interface that allows programs and
scripts to dynamically access and update the content, structure, and style of a document. It
defines the logical structure of documents and the way a document is accessed and
manipulated.

Note: It is called a Logical structure because DOM doesn’t specify any relationship between
objects.

DOM is a way to represent the webpage in a structured hierarchical way so that it will become
easier for programmers and users to glide through the document. With DOM, we can easily
access and manipulate tags, IDs, classes, Attributes, or Elements of HTML using commands
or methods provided by the Document object. Using DOM, the JavaScript gets access to
HTML as well as CSS of the web page and can also add behavior to the HTML elements. so
basically Document Object Model is an API that represents and interacts with HTML
or XML documents.

The DOM is a W3C (World Wide Web Consortium) standard.


The DOM defines a standard for accessing documents:
The W3C DOM standard is separated into 3 different parts:
• Core DOM - standard model for all document types
• XML DOM - standard model for XML documents
• HTML DOM - standard model for HTML documents

With the object model, JavaScript gets all the power it needs to create dynamic HTML:
• JavaScript can change all the HTML elements in the page
• JavaScript can change all the HTML attributes in the page
• JavaScript can change all the CSS styles in the page
• JavaScript can remove existing HTML elements and attributes
• JavaScript can add new HTML elements and attributes
• JavaScript can react to all existing HTML events in the page
• JavaScript can create new HTML events in the page

What is the HTML DOM?


The HTML DOM is a standard object model and programming interface for HTML. It
defines:
• The HTML elements as objects
• The properties of all HTML elements
• The methods to access all HTML elements
• The events for all HTML elements
In other words: The HTML DOM is a standard for how to get, change, add, or delete
HTML elements.

Why DOM is required?

HTML is used to structure the web pages and Javascript is used to add behavior to our web
pages. When an HTML file is loaded into the browser, the javascript can not understand the
HTML document directly. So, a corresponding document is created(DOM). DOM is
basically the representation of the same HTML document but in a different format with
the use of objects. Javascript interprets DOM easily i.e javascript can not understand the
tags(<h1>H</h1>) in HTML document but can understand object h1 in DOM. Now,
Javascript can access each of the objects (h1, p, etc) by using different functions.

Why called an Object Model?

Documents are modeled using objects, and the model includes not only the structure of a
document but also the behavior of a document and the objects of which it is composed like
tag elements with attributes in HTML.

Properties of DOM: Let’s see the properties of the document object that can be accessed
and modified by the document object.

Representation of the DOM


DOM Tree

DOM Nodes
• In DOM Tree the root or topmost object is called the Document Root.
• Each element within the HTML document is called a node. If the DOM is a tree, then
each node is an individual branch.
• There are:
1) Element nodes,
2) Text nodes,
3) Attribute nodes
• Window Object: Window Object is object of the browser which is always at top of the
hierarchy. It is like an API that is used to set and access all the properties and methods of
the browser. It is automatically created by the browser.
• Document object: When an HTML document is loaded into a window, it becomes a
document object. The ‘document’ object has various properties that refer to other objects
which allow access to and modification of the content of the web page. If there is a need
to access any element in an HTML page, we always start with accessing the ‘document’
object. Document object is property of window object.
• Form Object: It is represented by form tags.
• Link Object: It is represented by link tags.
• Anchor Object: It is represented by a href tags.
• Form Control Elements:: Form can have many control elements such as text fields,
buttons, radio buttons, checkboxes, etc.

Methods of Document Object:

• write(“string”): Writes the given string on the document.


• getElementById(): returns the element having the given id value.
• getElementsByName(): returns all the elements having the given name value.
• getElementsByTagName(): returns all the elements having the given tag name.
• getElementsByClassName(): returns all the elements having the given class name.
4.4 Window Object

The window object represents an open window in a browser. Window is the object of browser.
The window object is automatically created from the browser. All browsers support the
Window object.

If a document contain frames (<iframe> tags), the browser creates one window object for the
HTML document, and one additional window object for each frame.

Global variables are the properties of the Window objects, and global functions are the methods
of the Window object. The window object methods are used to retrieve the information from
the browser window.

Methods of window object

The important methods of window object are as follows:


Method Description

alert() displays the alert box containing message with ok button.

confirm() displays the confirm dialog box containing message with ok and cancel
button.

prompt() displays a dialog box to get input from the user.

open() opens the new window.

close() closes the current window.

setTimeout() performs action after specified time like calling function, evaluating
expressions etc.

blur() specifies a method that removes the focus from the current window.

clearInterval() specifies a method that clears the timer, which is set by using setInterval()
method.

focus() specifies a method that sets the focus on current window.

moveTo() specifies a method that moves a window to a specified position

moveBy() specifies a Method that moves a window relative to its current position.

print() specifies a method that sends a print command to print the content of the
current window.

setInterval() specifies a method that evaluates an expression at specified time intervals


(in milliseconds)
resizeBy() specifies the amount by which the window will be resized

resizeTo() used for dynamically resizing the window

scroll() scrolls the window to a particular place in document

scrollBy() scrolls the window by the given value

stop() this method stops window loading

Example of alert() in javascript

It displays alert dialog box. It has message and ok button.

<script type="text/javascript">
function msg(){
alert("Hello Alert Box");
}
</script>
<input type="button" value="click" onclick="msg()"/>

Example of confirm() in javascript

It displays the confirm dialog box. It has message with ok and cancel buttons.

<html>
<body>
<script type="text/javascript">
function msg(){
var v= confirm("Are u sure?");
if(v==true){
alert("ok");
}
else{
alert("cancel");
}

}
</script>

<input type="button" value="delete record" onclick="msg()"/>


</body>
</html>

Example of prompt() in javascript

It displays prompt dialog box for input. It has message and textfield.
<script type="text/javascript">
function msg(){
var v= prompt("Who are you?");
alert("I am "+v);

}
</script>
<input type="button" value="click" onclick="msg()"/>

Example of open() in javascript

It displays the content in a new window.

<script type="text/javascript">
function msg(){
open("http://www.javatpoint.com");
}
</script>
<input type="button" value="javatpoint" onclick="msg()"/>

Example of setTimeout() in javascript

It performs its task after the given milliseconds.

<script type="text/javascript">
function msg(){
setTimeout(
function(){
alert("Welcome to Javatpoint after 2 seconds")
},2000);

}
</script>
<input type="button" value="click" onclick="msg()"/>

4.5 Primitives

In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and
has no methods or properties.

There are seven primitive data types:


● string
● number
● bigint
● boolean
● undefined
● symbol
● null
The typeof operator tells you what type a primitive value is. To get the current type of the value
that the variable stores, you use the typeof operator.

String:

● In JavaScript, a string is a sequence of zero or more characters. A string literal begins


and ends with either a single quote(') or a double quote (").

Example:
let greeting = 'Hi';
let message = "Bye";

● If you want to single quote or double quotes in a literal string, you need to use the
backslash to escape it.

For example:
let message = 'I\'m also a valid string'; // use \ to escape the single quote (')

● JavaScript strings are immutable. This means that it cannot be modified once created.
However, you can create a new string from an existing string.

For example:
let str = 'JavaScript';
str = str + ' String';

In this example:
● First, declare the str variable and initialize it to a string of 'JavaScript'.
● Second, use the + operator to combine 'JavaScript' with ' String' to make its
value as 'Javascript String'.

● Behind the scene, the JavaScript engine creates a new string that holds the new
string 'JavaScript String' and destroys the original strings 'JavaScript' and ' String'.

The following example attempts to change the first character of the string JavaScript:

let s = 'JavaScript';
s[0] = 'j';
console.log(s)

The output is:


'JavaScript'

But not:
'javaScript'

Number:

● JavaScript uses the number type to represent both integer and floating-point numbers
(decimals and exponentials).
● The following statement declares a variable and initializes its value with an integer:
let num = 100;

● To represent a floating-point number, you include a decimal point followed by at least


one number.

For example:
let price= 12.5;
let discount = 0.05;

Exponential number example:


let number3 = 3e5 // 3 * 10^5

● Note that JavaScript automatically converts a floating-point number into an integer


number if the number appears to be a whole number.

● The reason is that Javascript always wants to use less memory since a floating-point
value uses twice as much memory as an integer value.

For example:
let price = 200.00; // interpreted as an integer 200

● To get the range of the number type, you use


Number.MIN_VALUE and Number.MAX_VALUE.

For example:
console.log(Number.MAX_VALUE); // 1.7976931348623157e+308
console.log(Number.MIN_VALUE); // 5e-324

● A number type can also be +Infinity, -Infinity, and NaN (not a number).

For example,
const number1 = 3/0;
console.log(number1); // Infinity

const number2 = -3/0;


console.log(number2); // -Infinity

// strings can't be divided by numbers


const number3 = "abc"/3;
console.log(number3); // NaN

bigint:

● The bigint type represents the whole numbers that are larger than 253 – 1. To form
a bigint literal number, you append the letter n at the end of the number.
For Example:
1. let pageView = 9007199254740991n;
console.log(typeof(pageView)); // 'bigint'
2. // Adding two big integersOut
const result1 = value1 + 1n;
console.log(result1); // "900719925124740999n"

3. // Error! BitInt and number cannot be added


const result2 = value2 + 1;
console.log(result2);
Output:
900719925124740999n
Uncaught TypeError: Cannot mix BigInt and other types
Boolean:

● The boolean type has two literal values: true and false in lowercase. The following
example declares two variables that hold the boolean values.

let inProgress = true;


let completed = false;
console.log(typeof completed); // boolean
● JavaScript allows values of other types to be converted into boolean values
of true or false. To convert a value of another data type into a boolean value, you use
the Boolean() function. The following table shows the conversion rules:

Type true false


string non-empty string empty string
number non-zero number and Infinity 0, NaN
object non-null object null
undefined undefined

For example:
console.log(Boolean('Hi'));// true
console.log(Boolean('')); // false
console.log(Boolean(20)); // true
console.log(Boolean(Infinity)); // true
console.log(Boolean(0)); // false
console.log(Boolean({foo: 100})); // true on non-empty object
console.log(Boolean(null));// false

Undefined:

● The undefined type is a primitive type that has only one value undefined.

● By default, when a variable is declared but not initialized, it is assigned the value
of undefined.

● Consider the following example:


let counter;
console.log(counter); // undefined
console.log(typeof counter); // undefined
In this example, the counter is a variable. Since counter hasn’t been initialized, it is
assigned the value undefined. The type of counter is also undefined.

● It’s important to note that the typeof operator also returns undefined when you call it
on a variable that hasn’t been declared:
Example: console.log(typeof undeclaredVar); // undefined
● It is also possible to explicitly assign a variable value undefined.
For example,
let name = undefined;
console.log(name); // undefined

● Note: It is recommended not to explicitly assign undefined to a variable.


Usually, null is used to assign 'unknown' or 'empty' value to a variable.

Symbol:

● Different from other primitive types, the symbol type does not have a literal form.

● A Symbol is a value created by invoking the Symbol function which is guaranteed to


create a unique value every time you call it.

● It takes one parameter, a string description, that will show up when you print the
symbol.
Example:
let x = Symbol("this is a symbol");
typeof x; // 'symbol'
console.log(Symbol() == Symbol()); // false

null:

● In JavaScript, null is a special value that represents empty or unknown value.

● The null type is the second primitive data type that also has only one value null.

For example,
let number = null;
console.log(typeof obj); // object

The code above suggests that the number variable is empty.

● Note: null is not the same as NULL or Null.

● JavaScript defines that null is equal to undefined as follows:


console.log(null == undefined); // true
4.6 Variables

Variables are containers for storing data (storing data values) that can be changed later on.

Declare a Variable

● In JavaScript, a variable can be declared using var, let, const keywords.


o var keyword is used to declare variables since JavaScript was created. It is
confusing and error-prone when using variables declared using var.
o let keyword removes the confusion and error of var. It is the new and
recommended way of declaring variables in JavaScript.
o const keyword is used to declare a constant variable that cannot be changed
once assigned a value.

4.7 Usage of let, var & const


● To declare a variable, write the keyword let followed by the name of the variable you
want to give, as shown below.
Example: Variable Declaration
let msg; // declaring a variable without assigning a value

In the above example, var msg; is a variable declaration. It does not have any value
yet.

● The default value of variables that do not have any value is undefined.

● You can assign a value to a variable using the = operator when you declare it or after
the declaration and before accessing it.
Example: Variable Initialization
let msg;
msg = "Hello JavaScript!"; // assigning a string value

In the above example, the msg variable is declared first and then assigned a string value
in the next line.

● You can declare a variable and assign a value to it in the same line. Values can be of
any datatype such as string, numeric, boolean, etc.

Example: Variable Declaration and Initialization


let name = "Steve"; //assigned string value
let num = 100; //assigned numeric value
let isActive = true; //assigned boolean value

● Multiple variables can be declared in a single line, as shown below.


Example: Multiple Variables
let name = "Steve", num = 100, isActive = true;

● You can copy the value of one variable to another variable, as shown below.
Example: Copy Variable
let num1 = 100;
let num2 = num1;

● JavaScript allows multiple white spaces and line breaks when you declare a variables.
Example: Whitespace and Line Breaks
let name = "Steve",
num = 100,
isActive = true;

● Variable names are case-sensitive in JavaScript. You cannot declare a duplicate


variable using the let keyword with the same name and case. JavaScript will throw a
syntax error. Although, variables can have the same name if declared with
the var keyword (this is why it is recommended to use let).

Example: Syntax Error


let num = 100;
let num = 200; //syntax error

var num = 100;


var num = 200; //Ok

The general rules for constructing names for variables (unique identifiers) are:
● Names can contain letters, digits, underscores, and dollar signs.
● Names must begin with a letter.
● Names can also begin with $ and _.
o These names are valid:
let $ = 1; // declared a variable with the name "$"
let _ = 2;
alert($ + _); // 3
● Names are case sensitive. So, the variable names msg, MSG, Msg, mSg are considered
separate variables.
● Reserved words (lik
● Dynamic Typing JavaScript keywords) cannot be used as names.
● JavaScript is a loosely typed language. It means that you don't need to specify what
data type a variable will contain.

● You can update the value of any type after initialization. It is also called dynamic
typing.
Example: Loosely Typed Variable
let myvariable = 1; // numeric value
myvariable = 'one'; // string value
myvariable = 1.1; // decimal value
myvariable = true; // Boolean value
myvariable = null; // null value

Constant Variables in JavaScript

● Use const keyword to declare a constant variable in JavaScript.

● Constant variables must be declared and initialized at the same time.


● The value of the constant variables can't be changed after initialized them.

Example: Constant Variables


const num = 100;
num = 200; //error

const name; //error


name = "Steve";

● The value of a constant variable cannot be changed but the content of the value can be
changed. For example, if an object is assigned to a const variable then the underlying
value of an object can be changed.

Example: Constant Variables


const person = { name: 'Steve'};
person.name = "Bill";
alert(person.name); //Bill

● It is best practice to give constant variable names in capital letters to separate them from
other non-constant variables.

Variable Scope

In JavaScript, a variable can be declared either in the global scope or the local scope.

Global Variables

Variables declared out of any function are called global variables. They can be accessed
anywhere in the JavaScript code, even inside any function.

Local Variables

Variables declared inside the function are called local variables of that function. They can only
be accessed in the function where they are declared but not outside.
The following example includes global and local variables.

Example: Global and Local Variable


let greet = "Hello " // global variable

function myfunction(){
let msg = "JavaScript!";
alert(greet + msg); //can access global and local variable
}

myfunction();

alert(greet);//can access global variable


alert(msg); //error: can't access local variable
Declare Variables without var and let Keywords

● Variables can be declared and initialized without the var or let keywords. However, a
value must be assigned to a variable declared without the var keyword.

● The variables declared without the var keyword become global variables, irrespective
of where they are declared.

● It is Recommended to declare variable using the let keyword.

Example: Variable Declaration Without var or let Keyword


function myfunction(){
msg = "Hello JavaScript!";
}

myfunction();
alert(msg); // msg becomes global variable so can be accessed here

Points to Remember:

1. Variables can be defined using let keyword. Variables defined


without let or var keyword become global variables.
2. Variables should be initialized before accessing it. Unassigned variable has
value undefined.
3. JavaScript is a loosely-typed language, so a variable can store any type value.
4. Variables can have local or global scope. Local variables cannot be accessed out of
the function where they are declared, whereas the global variables can be accessed
from anywhere.

4.8 Hoisting

• Hoisting in JavaScript is a behaviour in which a function or a variable can be used before


declaration.

• JavaScript Hoisting refers to the process whereby the interpreter appears to move
the declaration of functions, variables or classes to the top of their scope, prior to the
execution of the code.

Example:

console.log(test); // undefined
var test;

• In terms of variables and constants, keyword var is hoisted, and let and const do not
allow hoisting.

// program to display value


a = 5;
console.log(a);
var a; // 5

• In the above example, variable a is used before declaring it. And the program works
and displays the output 5. The program behaves as:
// program to display value
var a;
a = 5;
console.log(a); // 5

• However, in JavaScript, initializations are not hoisted. For example,

// program to display value


console.log(a);
var a = 5;

Output: undefined
• The above program behaves as:
var a;
console.log(a);
a = 5;

• Only the declaration is moved to the memory in the compile phase. Hence, the value of
variable a is undefined because a is printed without initializing it.

• When the interpreter hoists a variable declared with var, it initializes its value
to undefined.

The let and const Keywords

• Variables defined with let and const are hoisted to the top of the block, but
not initialized with a default value.

• Meaning: The block of code is aware of the variable, but it cannot be used until it has
been declared.

• Using a let variable before it is declared will result in a ReferenceError.

• The variable is in a "temporal dead zone" from the start of the block until it is declared:
a = 5;
console.log(a);
let a;

Output: Uncaught ReferenceError: Cannot access 'a' before initialization


• While using let, the variable must be declared first.
• With const, just as with let, the variable is hoisted to the top of the block.

• JavaScript only hoists declarations, not initializations.

console.log(hoist);
const hoist = 'The variable has been hoisted.';

Output: ReferenceError: hoist is not defined

• The interpreter throws an error if we use a constant before declaring and initializing it.

const PI;
console.log(PI);
PI=3.142;

Ouput: SyntaxError: Missing initializer in const declaration

• Therefore, a constant variable must be both declared and initialized before use.

Function Hoisting

A function can be called before declaring it. For example,

// program to print the text


greet();

function greet() {
console.log('Hi, there.');
}
Output: Hi, there

In the above program, the function greet is called before declaring it and the program shows
the output. This is due to hoisting.

when the variable is used inside the function, the variable is hoisted only to the top of the
function. For example,

// program to display value


var a = 4;

function greet() {
b = 'hello';
console.log(b); // hello
var b;
}

greet(); // hello
console.log(b);
Output
hello
Uncaught ReferenceError: b is not defined

• In the above example, variable b is hoisted to the top of the function greet and becomes
a local variable. Hence b is only accessible inside the function. b does not become a
global variable.

However, when a function is used as an expression, an error occurs because only declarations
are hoisted. For example;

// program to print the text


greet();

let greet = function() {


console.log('Hi, there.');
}
Output: Uncaught ReferenceError: greet is not defined

If var was used in the above program,

// program to print the text


greet();

var greet = function() {


console.log('Hi, there.');
}

The error would be:


Uncaught TypeError: greet is not a function
As we can see above, the variable declaration var greet is hoisted but it’s assignment to a
function is not. Therefore, the interpreter throws a TypeError since it sees greet as
a variable and not a function.

Summary
• JavaScript hoisting occurs during the creation phase of the execution context that moves
the variable and function declarations to the top of the script.
• The JavaScript engine hoists the variables declared using the let keyword, but it doesn’t
initialize them as the variables declared with the var keyword.
• The JavaScript engine doesn’t hoist the function expressions and arrow functions.

4.9 Typeof operator

In JavaScript, the typeof operator returns the data type of its operand in the form of a string.
The operand can be any object, function, or variable.
Syntax:
typeof operand
OR
typeof (operand)

Note: Operand is an expression representing the object or primitive whose type is to be


returned.

Example:
typeof "John" // Returns "string"
typeof 3.14 // Returns "number"
typeof NaN // Returns "number"
typeof false // Returns "boolean"
typeof [1,2,3,4] // Returns "object"
typeof {name:'John', age:34} // Returns "object"
typeof new Date() // Returns "object"
typeof function () {} // Returns "function"
typeof myCar // Returns "undefined" *
typeof null // Returns "object"

let type;
type = typeof 'Hi';
console.log(type); // 'string'

we will pass numbers as operands and use the typeof operator and log the result to the console.
We will use a positive integer, negative integer, zero, floating-point number, infinity, NaN, and
Math equations as operands. We will also use the concept to explicitly typecasting and parsing
a string to an integer or float and use it as an operand.

Example:
console.log(typeof 12) //number
console.log(typeof -31) //number

JavaScript typeof operator & parentheses

When passing an expression to the typeof operator, you need to use parentheses.

For example:
let type = typeof (100 + '10');
console.log(type);

Output:
'string'
In this example, the expression 100 + '10' returns the string '10010'. Therefore, its type
is 'string'. If you don’t use the parentheses, you’ll get an unexpected result.
For example:
let type = typeof 100 + '10';
console.log(type);

Output:
'number10'
In this example, the typeof 100 returns 'number'. Therefore, the result is a string that is the
concatenation of the string 'number' and '10'.

4.10 & 4.11 JavaScript Operators and Expressions


Operators are used to assign values, compare values, perform arithmetic operations, and
more.

An expression is a combination of values, variables, and operators, which computes to a


value.
The computation is called an evaluation.
For example, 5 * 10 evaluates to 50:

Operators

Arithmetic Operators
Arithmetic operators are used to perform arithmetic calculations.

Operator Name Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Remainder x%y

++ Increment (increments by 1) ++x or x++

-- Decrement (decrements by 1) --x or x--

** Exponentiation (Power) x ** y
Example Program:

<html>
<body>

<script type = "text/javascript">


<!--
var a = 33;
var b = 10;
var c = "Test";
var linebreak = "<br />";

document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);

document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);

document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);

document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);

document.write("a + b + c = ");
result = a + b + c;
document.write(result);
document.write(linebreak);

a = ++a;
document.write("++a = ");
result = ++a;
document.write(result);
document.write(linebreak);
b = --b;
document.write("--b = ");
result = --b;
document.write(result);
document.write(linebreak);
//-->
</script>
Set the variables to different values and then try...
</body>
</html>

Comparison Operators
Comparison operators compare two values and return a boolean value, either true or false.

Operator Description Example

== Equal to: returns true if the operands are equal x == y

!= Not equal to: returns true if the operands are not equal x != y

Strict equal to: true if the operands are equal and of


=== x === y
the same type

Strict not equal to: true if the operands are equal but
!== x !== y
of different type or not equal at all

Greater than: true if left operand is greater than the


> x>y
right operand

Greater than or equal to: true if left operand is greater


>= x >= y
than or equal to the right operand

Less than: true if the left operand is less than the right
< x<y
operand

Less than or equal to: true if the left operand is less


<= x <= y
than or equal to the right operand

Example Program:

<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";

document.write("(a == b) => ");


result = (a == b);
document.write(result);
document.write(linebreak);
document.write("(a < b) => ");
result = (a < b);
document.write(result);
document.write(linebreak);

document.write("(a > b) => ");


result = (a > b);
document.write(result);
document.write(linebreak);

document.write("(a != b) => ");


result = (a != b);
document.write(result);
document.write(linebreak);

document.write("(a >= b) => ");


result = (a >= b);
document.write(result);
document.write(linebreak);

document.write("(a <= b) => ");


result = (a <= b);
document.write(result);
document.write(linebreak);
//-->
</script>
Set the variables to different values and different operators and then try...
</body>
</html>

Logical Operators
Logical operators perform logical operations and return a boolean value, either true or false.

Operator Description Example

Logical AND: true if both the operands are true,


&& x && y
else returns false

Logical OR: true if either of the operands is true;


|| x || y
returns false if both are false

Logical NOT: true if the operand is false and vice-


! !x
versa.
<html>
<body>
<script type = "text/javascript">
<!--
var a = true;
var b = false;
var linebreak = "<br />";

document.write("(a && b) => ");


result = (a && b);
document.write(result);
document.write(linebreak);

document.write("(a || b) => ");


result = (a || b);
document.write(result);
document.write(linebreak);

document.write("!(a && b) => ");


result = (!(a && b));
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>

Bitwise Operators
Bitwise operators perform operations on binary representations of numbers.

Operator Description

& Bitwise AND

| Bitwise OR

^ Bitwise XOR

~ Bitwise NOT

<< Left shift


>> Sign-propagating right shift

>>> Zero-fill right shift

<html>
<body>
<script type = "text/javascript">
<!--
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11
var linebreak = "<br />";

document.write("(a & b) => ");


result = (a & b);
document.write(result);
document.write(linebreak);

document.write("(a | b) => ");


result = (a | b);
document.write(result);
document.write(linebreak);

document.write("(a ^ b) => ");


result = (a ^ b);
document.write(result);
document.write(linebreak);

document.write("(~b) => ");


result = (~b);
document.write(result);
document.write(linebreak);

document.write("(a << b) => ");


result = (a << b);
document.write(result);
document.write(linebreak);

document.write("(a >> b) => ");


result = (a >> b);
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Assignment Operators
Assignment operators are used to assign values to variables.

Operator Name Example

= Assignment operator a = 7; // 7

+= Addition assignment a += 5; // a = a + 5

-= Subtraction Assignment a -= 2; // a = a - 2

*= Multiplication Assignment a *= 3; // a = a * 3

/= Division Assignment a /= 2; // a = a / 2

%= Remainder Assignment a %= 2; // a = a % 2

**= Exponentiation Assignment a **= 2; // a = a**2

<html>
<body>
<script type = "text/javascript">
<!--
var a = 33;
var b = 10;
var linebreak = "<br />";

document.write("Value of a => (a = b) => ");


result = (a = b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a += b) => ");


result = (a += b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a -= b) => ");


result = (a -= b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a *= b) => ");


result = (a *= b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a /= b) => ");


result = (a /= b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a %= b) => ");


result = (a %= b);
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>

String Operators

In JavaScript, you can also use the + operator to concatenate (join) two or more strings.
The concatenation operator (+) concatenates two string values together, returning another
string that is the union of the two operand strings.

Note: When + is used with strings, it performs concatenation. However, when + is used with
numbers, it performs addition.

The shorthand assignment operator += can also be used to concatenate strings.

Example:
let a = 5, b = "Hello ", c = "World!", d = 10;

a + b; //returns "5Hello "

b + c; //returns "Hello World!"

a + d; //returns 15

b + true; //returns "Hello true"

c - b; //returns NaN; - operator can only used with numbers

<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript + Operator</h1>

<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<p id="p4"></p>
<p id="p5"></p>

<script>
let a = 5, b = "Hello ", c = "World!", d = 10;

document.getElementById("p1").innerHTML = a + b;

document.getElementById("p2").innerHTML = b + c;

document.getElementById("p3").innerHTML = a + d;

document.getElementById("p4").innerHTML = b + true;

document.getElementById("p5").innerHTML = c - b;

</script>
</body>
</html>

Other JavaScript Operators

Operator Description Example

evaluates multiple operands and returns the


, let a = (1, 3 , 4); // 4
value of the last operand.

(5 > 3) ? 'success' : 'error';


?: returns value based on the condition
// "success"

deletes an object's property, or an element of


delete delete x
an array

typeof returns a string indicating the data type typeof 3; // "number"

void discards the expression's return value void(x)

returns true if the specified property is in the


in prop in object
object

instance returns true if the specified object is of the object instanceof


of specified object type object_type
4.12 Difference between == and === operator in JavaScript
Both double equals == and triple equals === operator is used for comparing between two
values on which the operator is used on.

The difference between the two operators is that the double equals == will compare the
values loosely, meaning that it will try to convert values with different types before
comparing them.

The triple equals === won’t convert values of different types. It will simply return false when
comparing values of different types.
To understand their differences, let’s try comparing two different values between the number
value 0 and boolean value false:

As you can see from the code above, the == operator returns true because the boolean value
false is converted to a number before comparing it with 0.
On the other hand, the triple equals === will simply return false for the same values as above
because it doesn’t do conversion at all.

= == ===
=== is used for
= in JavaScript is used for == in JavaScript is used for comparing two variables,
assigning values to a comparing two variables, but it but this operator also
variable. ignores the datatype of variable. checks datatype and
compares two values.
It is called as assignment It is also called as
It is called as comparison operator
operator comparison operator
The assignment operator can
Checks the equality of two operands Compares equality of two
evaluate to the assigned
without considering their type. operands with their types.
value
= == ===
It returns true only if both
Return true if the two operands are
It does not return true or values and data types are
equal. It will return false if the two
false the same for the two
operands are not equal.
variables.
= simply assign one value of == make type correction based upon === takes type of
variable to another one. values of variables. variable in consideration.
If two variable values are
== will not compare the The == checks for equality only not similar, then === will
value of variables at all. after doing necessary conversations. not perform any
conversion.

KEY DIFFERENCES:

• = is used for assigning values to a variable, == is used for comparing two variables, but
it ignores the datatype of variable whereas === is used for comparing two variables,
but this operator also checks datatype and compares two values.
• = is called as assignment operator, == is called as comparison operator whereas === It
is also called as comparison operator.
• = does not return true or false, == Return true only if the two operands are equal while
=== returns true only if both values and data types are the same for the two variables.

Example:
var number = 100;
1. if (number == 100) // Here Comparision between two values using ==.It
will compare irrespective of datatype of variable
2. alert("Both are equal");
3. else
4. alert("Both are not equal");
Output: Both are equal

1. if (number == “100”) // Here Comparision between two values using ==.It


will compare irrespective of datatype of variable
2. alert("Both are equal");
3. else
4. alert("Both are not equal");

Output: Both are equal

1. if (number ===100) // Here Comparision between two values using ===. It will
compare strict check means it will check datatype as well.
2. alert("Both are equal");
3. else
4. alert("Both are not equal");

Output: Both are equal

In the above example, both the comparisons return a true value irrespective of datatype.
100==100 means both are int values and the other condition, 100 == "100" means int
comparison with "100" string type of variable still returns true. It means == is not doing a strict
type check.

1. if (number ===“100”) // Here Comparision between two values using ===. It


will compare strict check means it will check datatype as well.
2. alert("Both are equal");
3. else
4. alert("Both are not equal");

Output: Both are not equal

In the above code snippet, two variables are compared using === operator. It returns true for
100 === 100 and it returns false for 100 === "100". It means === does a strict check for
comparison. It checks datatype also and does a comparison based on it.

4.13 Screen Output & Keyboard Input


• The JavaScript model for the HTML document is the Document object
• The model for the browser display window is the Window object
o The Window object has two properties, document and window, which refer to
the document and window objects, respectively
• The Document object has a method, write, which dynamically creates content
o The parameter is a string, often catenated from parts, some of which are
variables
e.g., document.write("Answer: " + result + "<br />");
• The Window object has three methods for creating dialog boxes, alert,
confirm, and prompt
The default object for JavaScript is the Window object currently being displayed, so
calls to these methods need not include an object reference.
o alert("Hey! \n");
▪ Parameter is plain text, not HTML
▪ Opens a dialog box which displays the parameter string and
an OK button
o confirm("Do you want to continue?");
▪ Opens a dialog box and displays the parameter and two
buttons, OK and Cancel
o prompt("What is your name?", "");
▪ Opens a dialog box and displays its string parameter, along with a text
box and two buttons, OK and Cancel
▪ The second parameter is for a default response if the user
presses OK without typing a response in the text box (waits for OK)

Screen Output
JavaScript can "display" data in different ways:
● Writing into an HTML element, using innerHTML.
● Writing into the HTML output using document.write().
● Writing into an alert box, using window.alert().
● Writing into the browser console, using console.log().
i. Using innerHTML

You can use the innerHTML property of an HTML element to insert text into the element.
Before applying the innerHTML property, you need to select the element first.
Javascript has many methods to select an element from the HTML document. Some of these
are:
• Accessing elements using id, using getElementById("id") method.
• Accessing elements using CSS selectors, using querySelector("class") method.
• Accessing elements using tag name, using getElementSByTagName("tag") method.

Once you have selected the element, you can use the innerHTML property to insert text into
the element. The id attribute defines the HTML element. The innerHTML property defines the
HTML content.

Example:
<html>
<body>
<h2>My First Web Page</h2>
<p>My First Paragraph.</p>

<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>

Output

ii. Using document.write()

document.write() is a method using which you can write something on a webpage directly
using javascript. It is used for testing purposes.

Example:
<html>
<body>
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<p>Never call document.write after the document has finished loading.
It will overwrite the whole document.</p>
<script>
document.write(5 + 6);
</script>
</body>
</html>
Output

Note: document.write() method overwrites all of the things inside an HTML document, So be
careful while using it. Never use this method after the document is loaded (ex. using it in any
event trigger) otherwise it will overwrite all.
iii. Using window.alert()

document.alert() or alert() method is used to show some output or result. It creates a pop up
showing the result.
When an alert pop up appears on the screen then any program after the alert() method is not
executed until the pop up is closed.

Example:
<html>
<body>
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>

Output

iv. Using console.log()

For debugging purposes, you can call the console.log() method in the browser to display
data/results in the console.
Example:
<html>
<body>
<h2>Activate Debugging</h2>
<p>F12 on your keyboard will activate debugging.</p>
<p>Then select "Console" in the debugger menu.</p>
<p>Then click Run again.</p>
<script>
console.log(5 + 6);
</script>
</body>
</html>

Keyboard Input

• The prompt() method in JavaScript is used to display a prompt box that prompts the
user for the input.
• It is generally used to take the input from the user before entering the page. It can be
written without using the window prefix.
• When the prompt box pops up, we have to click "OK" or "Cancel" to proceed.

• The box is displayed using the prompt() method, which takes two arguments: The first
argument is the label which displays in the text box, and the second argument is the
default string, which displays in the textbox.
• The prompt box consists of two buttons, OK and Cancel.
• It returns null or the string entered by the user.
• When the user clicks "OK," the box returns the input value. Otherwise, it returns null
on clicking "Cancel".

Syntax
prompt(message, default)

message: It is an optional parameter. It is the text displays to the user. We can omit this value
if we don't require to show anything in the prompt.
default: It is also an optional parameter. It is a string that contains the default value displayed
in the textbox.

Example:
<html>
<head>
<script type = "text/javascript">
function fun() {
prompt ("This is a prompt box", "Hello world");
}
</script>
</head>
<body>
<p> Click the following button to see the effect </p>
<form>
<input type = "button" value = "Click me" onclick = "fun();" />
</form>
</body>
</html>

4.14 Control Statements

Control structure actually controls the flow of execution of a program. Following are the
several control structure supported by javascript.
• if … else
• switch case
• do while loop
• while loop
• for loop

If … else
The if statement is the fundamental control statement that allows JavaScript to make decisions
and execute statements conditionally.
Syntax
if (expression){
Statement(s) to be executed if expression is true
}
Example
<script type="text/javascript">
<!--
var age = 20;
if( age > 18 ){
document.write("<b>Qualifies for driving</b>");
}
//-->
</script>

Switch case
The basic syntax of the switch statement is to give an expression to evaluate and several
different statements to execute based on the value of the expression. The interpreter checks
each case against the value of the expression until a match is found. If nothing matches, a
default condition will be used.
Syntax
switch (expression) {
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}

Example
<script type="text/javascript">
<!--
var grade='A';
document.write("Entering switch block<br/>");
switch (grade) {
case 'A': document.write("Good job<br/>");
break;
case 'B': document.write("Pretty good<br/>");
break;
case 'C': document.write("Passed<br/>");
break;
case 'D': document.write("Not so good<br/>");
break;
case 'F': document.write("Failed<br/>");
break;
default: document.write("Unknown grade<br/>")
}
document.write("Exiting switch block");
//-->
</script>

Do while Loop
The do...while loop is similar to the while loop except that the condition check happens at the
end of the loop. This means that the loop will always be executed at least once, even if the
condition is false.
Syntax
do{
Statement(s) to be executed;
} while (expression);
Example
<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop" + "<br/>");
do{
document.write("Current Count : " + count + "<br/>");
count++;
}while (count < 0);
document.write("Loop stopped!");
//-->
</script>
This will produce following result −
Starting Loop
Current Count : 0
Loop stopped!

While Loop
The purpose of a while loop is to execute a statement or code block repeatedly as long as
expression is true. Once expression becomes false, the loop will be exited.
Syntax
while (expression){
Statement(s) to be executed if expression is true
}
Example
<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop" + "<br/>");
while (count < 10){
document.write("Current Count : " + count + "<br/>");
count++;
}
document.write("Loop stopped!");
//-->
</script>
This will produce following result −
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!

For Loop
The for loop is the most compact form of looping and includes the following three important
parts −
• The loop initialization where we initialize our counter to a starting value. The
initialization statement is executed before the loop begins.
• The test statement which will test if the given condition is true or not. If condition is
true then code given inside the loop will be executed otherwise loop will come out.
• The iteration statement where you can increase or decrease your counter.

Syntax
for (initialization; test condition; iteration statement){
Statement(s) to be executed if test condition is true
}
Example
<script type="text/javascript">
<!--
var count;
document.write("Starting Loop" + "<br/>");
for(count = 0; count < 10; count++){
document.write("Current Count : " + count );
document.write("<br/>");
}
document.write("Loop stopped!");
//-->
</script>
This will produce following result which is similar to while loop −
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!

Creating Sample Program

Following is the sample program that shows time, when we click in button.
<html>
<body>
<button onclick="this.innerHTML=Date()">The time is?</button>
<p>Click to display the date.</p>
<button onclick="displayDate()">The time is?</button>
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}</script>

<p id="demo"></p>
</script>
</body>
</html>
Output

4.15 & 4.16 Arrays

An array is a special variable, which can hold more than one value.
JavaScript array is an object that represents a collection of similar type of elements.

There are 3 ways to construct array in JavaScript


1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)

1) JavaScript array literal

The syntax of creating array using array literal is given below:


let arrayname=[value1,value2.....valueN];

Example:
<html>
<body>
<script>
let emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
</body>
</html>

Output:
Sonoo
Vimal
Ratan

2) JavaScript Array directly (new keyword)

The syntax of creating array directly is given below:


let arrayname=new Array();
Here, new keyword is used to create instance of array.

Example:
<html>
<body>
<script>
let i;
let emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";

for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
</body>
</html>

Output:
Arun
Varun
John

3) JavaScript array constructor (new keyword)

Here, you need to create instance of array by passing arguments in constructor so that we don't
have to provide value explicitly.

The syntax of creating array using constructor is given below:


let arrayname=new Array(value1,value2.....valueN);

Example:
<html>
<body>
<script>
let emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
</body>
</html>

Output:
Jai
Vijay
Smith

An array in JavaScript can hold different elements that can store Numbers, Strings, and
Boolean in a single array.

// Storing number, boolean, strings in an Array


let house = ["1BHK", 25000, "2BHK", 50000, "Rent", true];
console.log(house)

Output:
["1BHK", 25000, "2BHK", 50000, "Rent", true]

Accessing Array Elements of an Array in JavaScript are indexed from 0 so we can access
array elements as follows.

let house = ["1BHK", 25000, "2BHK", 50000, "Rent", true];


console.log(house[0]+" cost= "+house[1]);
let cost_1BHK = house[1];
let is_for_rent = house[5];
console.log("Cost of 1BHK = "+ cost_1BHK);
console.log("Is house for rent = ")+ is_for_rent;

Output:
"1BHK cost= 25000"
"Cost of 1BHK = 25000"
"Is house for rent = true"

Changing an Array Element

Example
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";

Length property of an Array returns the length of an Array. The length of an Array is
always one more than the highest index of an Array.

let house = ["1BHK", 25000, "2BHK", 50000, "Rent", true];


// len contains the length of the array
let len = house.length;
for (let i = 0; i < len; i++)
console.log(house[i]);//Output 1BHK

Output:
"1BHK"
25000
"2BHK"
50000
"Rent"
True

Get last elements with “at”


To access the last element of the array or to read the elements in reverse order(ie. From last
element to first element), we can use at().
Example:
let fruits = ["Apple", "Orange", "Plum"];

// same as fruits[fruits.length-1]
alert( fruits.at(-1) ); // Plum

In other words, arr.at(i):


• is exactly the same as arr[i], if i >= 0.
• for negative values of i, it steps back from the end of the array.
Arrays in JavaScript can work both as a queue and as a stack. They allow you to
add/remove elements, both to/from the beginning or the end.

Methods that work with the end of the array:

pop
Extracts the last element of the array and returns it:

let fruits = ["Apple", "Orange", "Pear"];


alert( fruits.pop() ); // remove "Pear" and alert it
alert( fruits ); // Apple, Orange

Both fruits.pop() and fruits.at(-1) return the last element of the array, but fruits.pop() also
modifies the array by removing it.

push
Append the element to the end of the array:

let fruits = ["Apple", "Orange"];


fruits.push("Pear");
alert( fruits ); // Apple, Orange, Pear

The call fruits.push(...) is equal to fruits[fruits.length] = ....

Methods that work with the beginning of the array:

shift
Extracts the first element of the array and returns it:
let fruits = ["Apple", "Orange", "Pear"];
alert( fruits.shift() ); // remove Apple and alert it
alert( fruits ); // Orange, Pear

unshift
Add the element to the beginning of the array:

let fruits = ["Orange", "Pear"];


fruits.unshift('Apple');
alert( fruits ); // Apple, Orange, Pear

Methods push and unshift can add multiple elements at once:

let fruits = ["Apple"];


fruits.push("Orange", "Peach");
fruits.unshift("Pineapple", "Lemon");
// ["Pineapple", "Lemon", "Apple", "Orange", "Peach"]
alert( fruits );

Looping Array Elements


One way to loop through an array, is using a for loop:
Example:
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Arrays</h2>

<p>The best way to loop through an array is using a standard for loop:</p>

<p id="demo"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fLen = fruits.length;

let text = "<ul>";


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

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Output:
JavaScript Arrays
The best way to loop through an array is using a standard for loop:
• Banana
• Orange
• Apple
• Mango

You can also use the Array.forEach() function:

Example:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The forEach() Method</h2>
<p>Array.forEach() calls a function for each array element.</p>

<p id="demo"></p>

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

let text = "<ul>";


fruits.forEach(myFunction);
text += "</ul>";

document.getElementById("demo").innerHTML = text;

function myFunction(value) {
text += "<li>" + value + "</li>";
}
</script>

</body>
</html>

Output:
JavaScript Arrays

The forEach() Method


Array.forEach() calls a function for each array element.
• Banana
• Orange
• Apple
• Mango

But for arrays there is another form of loop, for..of:

let fruits = ["Apple", "Orange", "Plum"];


// iterates over array elements
for (let fruit of fruits) {
alert( fruit );
}

Note:
JavaScript does not support arrays with named indexes.
In JavaScript, arrays always use numbered indexes.

JavaScript Array Methods


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.
isArray() It tests if the passed value ia an array.

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

keys() It creates an iterator object that contains only the keys of the array, then
loops through these keys.

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

of() It creates a new array from a variable number of arguments, holding any
type of argument.

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

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

reverse() It reverses the elements of given array.

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

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

some() It determines if any element of the array passes the test of the
implemented function.

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.

splice() It add/remove elements to/from the given array.

toLocaleString() It returns a string containing all the elements of a specified 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.

4.17 MAP
• JavaScript ES6 has introduced two new data structures, i.e Map and WeakMap.

• Map is a collection of elements where each element is stored as a Key, value pair.

• Map object can hold both objects and primitive values as either key or value.

• A Map remembers the original insertion order of the keys.

• When we iterate over the map object it returns the key, value pair in the same order
as inserted.

• Syntax : new Map([iterable])


iterable represents an array and other iterable object whose elements are in the form of
key-value pair.

• //Example
let map1 = new Map();
map1.set('info', {name: 'Jack', age: 26});
console.log(map1);

• A Map has a property that represents the size of the map.

JavaScript Map Size


console.log(map1.size);

• Iterate Through a Map


let map1 = new Map();
map1.set('name', 'Jack');
map1.set('age', '27');
for (let [key, value] of map1)
{ console.log(key + '- ' + value); }

(OR) // Instead of for

map1.forEach(function(value, key) { console.log(key + '- ' + value)

Map Methods
Method Description

new Map() Creates a new Map object

set() Sets the value for a key in a Map

get() Gets the value for a key in a Map

clear() Removes all the elements from a Map

delete() Removes a Map element specified by a key


has() Returns true if a key exists in a Map

forEach() Invokes a callback for each key/value pair in a Map

entries() Returns an iterator object with the [key, value] pairs in a Map

keys() Returns an iterator object with the keys in a Map

values() Returns an iterator object of the values in a Map

Property Description

size Returns the number of Map elements

Points to remember

o A map object cannot contain the duplicate keys.


o A map object can contain the duplicate values.
o The key and value can be of any type (allows both object and primitive values).
o A map object iterates its elements in insertion order.

Difference between Map and Object.

Map Object
Maps can contain objects and other data Objects can only contain strings and symbols
types as keys. as keys.
Maps can be directly iterated and their value Objects can be iterated by accessing its keys.
can be accessed.
The number of elements of a Map can be The number of elements of an object needs to
determined by size property. be determined manually.
Map performs better for programs that Object does not perform well if the program
require the addition or removal of elements requires the addition or removal of elements
frequently. frequently.

4.18 & 4.19 Strings


JavaScript strings are for storing and manipulating text.
A JavaScript string is zero or more characters written inside quotes.
Example
let text = "John Doe";

You can use single or double quotes:


Example
let carName1 = "Volvo XC60"; // Double quotes
let carName2 = 'Volvo XC60'; // Single quotes

You can use quotes inside a string, as long as they don't match the quotes surrounding
the string:
Example
let answer1 = "It's alright";
let answer2 = "He is called 'Johnny'";
let answer3 = 'He is called "Johnny"';

String Methods
● String length
● String slice()
● String substring()
● String substr()
● String replace()
● String replaceAll()
● String toUpperCase()
● String toLowerCase()
● String concat()
● String trim()
● String trimStart()
● String trimEnd()
● String padStart()
● String padEnd()
● String charAt()
● String charCodeAt()
● String split()

String Length

The length property returns the length of a string:


let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = text.length;

Output: 26

Extracting String Parts


There are 3 methods for extracting a part of a string:
• slice(start, end)
• substring(start, end)
• substr(start, length)
• slice() extracts a part of a string and returns the extracted part in a new string.
• The method takes 2 parameters: start position, and end position (end not included).

String slice()

slice() extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters: start position, and end position

Example
Slice out a portion of a string from position 7 to position 13:
let text = "Apple, Banana, Kiwi";
let part = text.slice (7, 13);

Output: Banana
JavaScript counts positions from zero.
First position is 0.
Second position is 1

If you omit the second parameter, the method will slice out the rest of the string:
let text = "Apple, Banana, Kiwi";
let part = text.slice(7);

Output:
Banana, Kiwi
If a parameter is negative, the position is counted from the end of the string:
let text = "Apple, Banana, Kiwi";
let part = text.slice(-12);

Output:
Banana, Kiwi

This example slices out a portion of a string from position -12 to position -6:
let text = "Apple, Banana, Kiwi";
let part = text.slice(-12, -6);

Output:
Banana

String substring()

substring() is similar to slice().The difference is that start and end values less than 0 are
treated as 0 in substring().

Example
let str = "Apple, Banana, Kiwi";
let part = str.substring(7, 13);

Output: Banana

If you omit the second parameter, substring() will slice out the rest of the string.

String substr()

substr() is similar to slice().The difference is that the second parameter specifies the length of
the extracted part.

let str = "Apple, Banana, Kiwi";


let part = str.substr(7, 6);

Output: Banana

If you omit the second parameter, substr() will slice out the rest of the string.
let str = "Apple, Banana, Kiwi";
let part = str.substr(7);

Output: Banana, Kiwi

If the first parameter is negative, the position counts from the end of the string.

Example
let str = "Apple, Banana, Kiwi";
let part = str.substr(-4);

Output: Kiwi

Replacing String Content

The replace() method replaces a specified value with another value in a string:

Example
let text = "Please visit Microsoft!";
let newText = text.replace("Microsoft", "W3Schools");

Output:
Please visit W3Schools!

Note
The replace() method does not change the string it is called on.
The replace() method returns a new string.
The replace() method replaces only the first match

If you want to replace all matches, use a regular expression with the /g flag set.
By default, the replace() method replaces only the first match:

let text = "Please visit Microsoft and Microsoft!";


let newText = text.replace("Microsoft", "W3Schools");

Output:
Please visit W3Schools and Microsoft!

By default, the replace() method is case sensitive. Writing MICROSOFT (with upper-case)
will not work:

let text = "Please visit Microsoft!";


let newText = text.replace("MICROSOFT", "W3Schools");

Output:
Please visit Microsoft!

To replace case insensitive, use a regular expression with an /i flag (insensitive):


let text = "Please visit Microsoft!";
let newText = text.replace(/MICROSOFT/i, "W3Schools");
Output:
Please visit W3Schools!

To replace all matches, use a regular expression with a /g flag (global match):
Example
let text = "Please visit Microsoft and Microsoft!";
let newText = text.replace(/Microsoft/g, "W3Schools");

Output:
Please visit W3Schools and W3Schools!
String ReplaceAll()

let text = "I love cats. Cats are very easy to love. Cats are very popular."
text = text.replaceAll("Cats","Dogs");
text = text.replaceAll("cats","dogs");

document.getElementById("demo").innerHTML = text;

Output:
I love dogs. Dogs are very easy to love. Dogs are very popular.

The replaceAll() method allows you to specify a regular expression instead of a string to be
replaced.
If the parameter is a regular expression, the global flag (g) must be set set, otherwise a
TypeError is thrown.

text = text.replaceAll(/Cats/g,"Dogs");
text = text.replaceAll(/cats/g,"dogs");

Converting to Upper and Lower Case

A string is converted to upper case with toUpperCase():


A string is converted to lower case with toLowerCase():

toUpperCase()

let text1 = "Hello World!";


let text2 = text1.toUpperCase();

Output:
HELLO WORLD!

toLowerCase()

let text1 = "Hello World!"; // String


let text2 = text1.toLowerCase(); // text2 is text1 converted to lower

Output:
hello world!
concat()

concat() joins two or more strings:

Example
let text1 = "Hello";
let text2 = "World";
let text3 = text1.concat(" ", text2);

Output:
Hello World!

The concat() method can be used instead of the plus operator. These two lines do the same:
Example
text = "Hello" + " " + "World!";
text = "Hello".concat(" ", "World!");

Note
All string methods return a new string. They don't modify the original string.
Formally said:
Strings are immutable: Strings cannot be changed, only replaced.

trim()

The trim() method removes whitespace from both sides of a string:


Example
let text1 = " Hello World! ";
let text2 = text1.trim();

Output:
Length text1 = 22
Length text2 = 12

trimStart()

The trimStart() method works like trim(), but removes whitespace only from the start of a
string.
Example
let text1 = " Hello World! ";
let text2 = text1.trimStart();

Output:
Length text1 = 22
Length text2 = 17
trimEnd()

The trimEnd() method works like trim(), but removes whitespace only from the end of a
string.
Example
let text1 = " Hello World! ";
let text2 = text1.trimEnd();

Output:
Length text1 = 22
Length text2 = 17

String Padding

Two String methods: padStart() and padEnd() supports padding at the beginning and at the
end of a string.

padStart()

The padStart() method pads a string with another string:


Example
let text = "5";
let padded = text.padStart(4,"x");

Output:
xxx5

Example
let text = "5";
let padded = text.padStart(4,"0");

Output:
0005

Note
The padStart() method is a string method.
To pad a number, convert the number to a string first.

let numb = 5;
let text = numb.toString();
let padded = text.padStart(4,"0");

Output:
0005

padEnd()

The padEnd() method pads a string with another string:


Example
let text = "5";
let padded = text.padEnd(4,"x");

Output:
5xxx
Extracting String Characters

There are 2 methods for extracting string characters:


• charAt(position)
• charCodeAt(position)

charAt()

The charAt() method returns the character at a specified index (position) in a string:
Example
let text = "HELLO WORLD";
let char = text.charAt(0);

Output:
H

charCodeAt()

The charCodeAt() method returns the unicode of the character at a specified index in a string:
The method returns a UTF-16 code (an integer between 0 and 65535).
Example
let text = "HELLO WORLD";
let char = text.charCodeAt(0);
Output:
72

split()

A string can be converted to an array with the split() method:


Example
text.split(",") // Split on commas
text.split(" ") // Split on spaces
text.split("|") // Split on pipe

Example:
let text = "a,b,c,d,e,f";
const myArray = text.split(",");
document.getElementById("demo").innerHTML = myArray[0];

Output:
a

If the separator is omitted, the returned array will contain the whole string in index[0].

If the separator is "", the returned array will be an array of single characters:
let text = "Hello";
const myArr = text.split("");

text = "";
for (let i = 0; i < myArr.length; i++) {
text += myArr[i] + "<br>"
}
document.getElementById("demo").innerHTML = text;

Output:
H
e
l
l
o

4.20 JavaScriptObject
• We know that JavaScript variables are containers for data values.
• This code assigns a simple value (Fiat) to a variable named car:
o let car = "Fiat";
• Objects are variables too. But objects can contain many values.
• This code assigns many values (Fiat, 500, white) to a variable named car:
o const car = {type:"Fiat", model:"500", color:"white"};
• The values are written as name:value pairs (name and value separated by a colon).

• JavaScript object is a non-primitive data-type that allows you to store multiple


collections of data.
• In JavaScript, an object is an unordered collection of key-value pairs. Each key-value
pair is called a property.
• The key of a property can be a string. And the value of a property can be any value,
e.g., a string, a number, an array, and even a function.
• JavaScript provides you with many ways to create an object. The most commonly used
one is to use the object literal notation.

The following example creates an empty object using the object literal notation:
let empty = {};
To create an object with properties, you use the key:value within the curly braces.

For example, the following creates a new person object:


let person = {
firstName: 'John',
lastName: 'Doe'
};

The person object has two properties firstName and lastName with the corresponding
values 'John' and 'Doe'.
When an object has multiple properties, you use a comma (,) to separate them like the above
example.

Accessing properties
To access a property of an object, you use one of two notations: the dot notation and array-
like notation.

1) The dot notation (.)

The following illustrates how to use the dot notation to access a property of an object:
objectName.propertyName
For example, to access the firstName property of the person object, you use the following
expression:
person.firstName
This example creates a person object and shows the first name and last name to the console:
let person = {
firstName: 'John',
lastName: 'Doe'
};

console.log(person.firstName);
console.log(person.lastName);

2) Array-like notation ([])

The following illustrates how to access the value of an object’s property via the array-like
notation:
objectName['propertyName']
For example:
let person = {
firstName: 'John',
lastName: 'Doe'
};

console.log(person['firstName']);
console.log(person['lastName']);

When a property name contains spaces, you need to place it inside quotes.

For example, the following address object has the 'building no' as a property:
let address = {
'building no': 3960,
street: 'North 1st street',
state: 'CA',
country: 'USA'
};

To access the 'building no' property, you need to use the array-like notation:
address['building no'];
If you use the dot notation, you’ll get an error:
address.'building no';

Error:
SyntaxError: Unexpected string

Note that it is not a good practice to use spaces in the property names of an object.
Reading from a property that does not exist will result in an undefined. For example:
console.log(address.district);
Output:
undefined
Modifying the value of a property

To change the value of a property, you use the assignment operator (=). For example:
let person = {
firstName: 'John',
lastName: 'Doe'
};

person.firstName = 'Jane';
console.log(person);

Output:
{ firstName: 'Jane', lastName: 'Doe' }
In this example, we changed the value of the firstName property of the person object
from 'John' to 'Jane'.

Adding a new property to an object

Unlike objects in other programming languages such as Java and C#, you can add a property
to an object after object creation.
The following statement adds the age property to the person object and assigns 25 to it:
person.age = 25;
Deleting a property of an object

To delete a property of an object, you use the delete operator:


delete objectName.propertyName;
The following example removes the age property from the person object:
delete person.age;
If you attempt to reaccess the age property, you’ll get an undefined value.

Checking if a property exists


To check if a property exists in an object, you use the in operator:
propertyName in objectName
The in operator returns true if the propertyName exists in the objectName.
The following example creates an employee object and uses the in operator to check if
the ssn and employeeId properties exist in the object:
let employee = {
firstName: 'Peter',
lastName: 'Doe',
employeeId: 1
};

console.log('ssn' in employee);
console.log('employeeId' in employee);

Output:
false
true

Summary
• An object is a collection of key-value pairs.
• Use the dot notation ( .) or array-like notation ([]) to access a property of an object.
• The delete operator removes a property from an object.
• The in operator check if a property exists in an object.

JavaScript Nested Objects


An object can also contain another object. For example,
// nested object
const student = {
name: 'John',
age: 20,
marks: {
science: 70,
math: 75
}
}

// accessing property of student object


console.log(student.marks); // {science: 70, math: 75}

// accessing property of marks object


console.log(student.marks.science); // 70

In the above example, an object student contains an object value in the marks property.

JavaScript Object Methods

In JavaScript, an object can also contain a function. For example,


const person = {
name: 'Sam',
age: 30,
// using function as a value
greet: function() { console.log('hello') }
}
person.greet(); // hello

Here, a function is used as a value for the greet key. That's why we need to
use person.greet() instead of person.greet to call the function inside the object.
A JavaScript method is a property containing a function declaration.

Example
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};

In the example above, this refers to the person object.


i.e., this.firstName means the firstName property of this.
i.e., this.firstName means the firstName property of person.

4.21 Regular Expressions


A regular expression is a sequence of characters that forms a search pattern. The search
pattern can be used for text search and text to replace operations. A regular expression can
be a single character or a more complicated pattern. Regular expressions can be used to
perform all types of text search and text replacement operations.
Syntax:
/pattern/modifiers;
Example:
let patt = /GeeksforGeeks/i;
Explanation :
/GeeksforGeeks/i is a regular expression.
GeeksforGeeks is the pattern (to be used in a search).
i is a modifier (modifies the search to be Case-Insensitive).
Regular Expression Modifiers can be used to perform multiline searches which can also be
set to case-insensitive matching:

Expressions Descriptions

g Find the character globally

i Find a character with case-insensitive matching

m Find multiline matching


Regular Expression Brackets can be Find characters in a specified range

Expressions Description

[abc] Find any of the characters inside the brackets

[^abc] Find any character, not inside the brackets

[0-9] Find any of the digits between the brackets 0 to 9

[^0-9] Find any digit not in between the brackets

(x | y) Find any of the alternatives between x or y separated with |

Regular Expression Metacharacters are characters with a special meaning:

Metacharacter Description

\. Search single characters, except line terminator or newline.

\w Find the word character i.e. characters from a to z, A to Z, 0 to 9

\d Find a digit

\D Search non-digit characters i.e all the characters except digits

\s Find a whitespace character

\S Find the non-whitespace characters.

\b Find a match at the beginning or at the end of a word

\B Find a match that is not present at the beginning or end of a word.

\0 Find the NULL character.

\n Find the newline character.

\f Find the form feed character


Metacharacter Description

\r Find the carriage return character

\t Find the tab character

\v Find the vertical tab character

\uxxxx Find the Unicode character specified by the hexadecimal number xxxxx

Regular Expression Quantifiers are used to define quantities occurrence

Quantifier Description

n+ Match any string that contains at least one n

n* Match any string that contains zero or more occurrences of n

n? Match any string that contains zero or one occurrence of n

m{X} Find the match of any string that contains a sequence of m, X times

m{X, Y} Find the match of any string that contains a sequence of m, X to Y times

m{X,} Find the match of any string that contains a sequence of m, at least X times

m$ Find the match of any string which contains m at the end of it

^m Find the match of any string which contains m at the beginning of it

?!m Find the match of any string which is not followed by a specific string m.

Regular Expression Object Properties:

Property Description

constructor Return the function that created the RegExp object’s prototype
Property Description

global Specify whether the “g” modifier is set or not

ignorecase Specify whether the “i” modifier is set or not

lastindex Specify the index at which to start the next match

multiline Specify whether the “m” modifier is set or not

source Return the text of RegExp pattern

Regular Expression Object Methods:

Method Description

compile() Used to compile the regular expression while executing of script

exec() Used to test for the match in a string.

test() Used to test for a match in a string

toString() Return the string value of the regular expression

Below is an example of the JavaScript Regular Expressions.


Example:
function GFGFun() {
var str = "Visit geeksforGeeks";
var n = str.search(/GeeksforGeeks/i);
console.log(n);
}
GFGFun();
Output:
6

Using String Methods: In JavaScript, regular expressions are often used with the two string
methods: search() and replace().
• The search() method uses an expression to search for a match and returns the
position of the match.
• The replace() method returns a modified string where the pattern is replaced.

Using String search() With a Regular Expression: Use a regular expression to do a case-
insensitive search for “GeeksforGeeks” in a string:

Example:
function myFunction() {

// input string
var str = "Visit geeksforGeeks!";

// searching string with modifier i


var n = str.search(/GeeksforGeeks/i);

console.log(n);

// searching string without modifier i


var n = str.search(/GeeksforGeeks/);

console.log(n);
}
myFunction();

Output:
6
-1
Use String replace() With a Regular Expression : Use a case insensitive regular expression
to replace gfG with GeeksforGeeks in a string:

Example:
function myFunction() {

// input string
var str = "Please visit gfG!";

// replacing with modifier i


var txt = str.replace(/gfg/i, "geeksforgeeks");

console.log(txt);
}
myFunction();

Output:
Please visit geeksforgeeks!

Example 1: Regular Expressions


const string = 'Find me';
const pattern = /me/;
// search if the pattern is in string variable
const result1 = string.search(pattern);
console.log(result1); // 5

// replace the character with another character


const string1 = 'Find me';
string1.replace(pattern, 'found you'); // Find found you

// splitting strings into array elements


const regex1 = /[\s,]+/;
const result2 = 'Hello world! '.split(regex1);
console.log(result2); // ['Hello', 'world!', '']

// searching the phone number pattern


const regex2 = /(\d{3})\D(\d{3})-(\d{4})/g;
const result3 = regex2.exec('My phone number is: 555 123-4567.');
console.log(result3); // ["555 123-4567", "555", "123", "4567"]

Example 2: Regular Expression Modifier


const string = 'Hello hello hello';

// performing a replacement
const result1 = string.replace(/hello/, 'world');
console.log(result1); // Hello world hello

// performing global replacement


const result2 = string.replace(/hello/g, 'world');
console.log(result2); // Hello world world

// performing case-insensitive replacement


const result3 = string.replace(/hello/i, 'world');
console.log(result3); // world hello hello

// performing global case-insensitive replacement


const result4 = string.replace(/hello/gi, 'world');
console.log(result4); // world world world

Example 3: Validating the Phone Number


// program to validate the phone number

function validatePhone(num) {

// regex pattern for phone number


const re = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/g;
// check if the phone number is valid
let result = num.match(re);
if (result) {
console.log('The number is valid.');
}
else {
let num = prompt('Enter number in XXX-XXX-XXXX format:');
validatePhone(num);
}
}

// take input
let number = prompt('Enter a number XXX-XXX-XXXX');

validatePhone(number);
Output
Enter a number XXX-XXX-XXXX: 2343223432
Enter number in XXX-XXX-XXXX format: 234-322-3432
The number is valid

Example 4: Validating the Email Address


// program to validate the email address

function validateEmail(email) {

// regex pattern for email


const re = /\S+@\S+\.\S+/g;

// check if the email is valid


let result = re.test(email);
if (result) {
console.log('The email is valid.');
}
else {
let newEmail = prompt('Enter a valid email:');
validateEmail(newEmail);
}
}

// take input
let email = prompt('Enter an email: ');
validateEmail(email);

Output
Enter an email: hellohello
Enter a valid email: learningJS@gmail.com
The email is valid.

You might also like