[Go to site: main page, start]

0% found this document useful (0 votes)
1 views38 pages

Unit-4 (Java Script)

JavaScript is a versatile programming language primarily used for web development, enabling dynamic interaction with web pages through the ECMAScript, DOM, and BOM. It can run both client-side in web browsers and server-side using environments like Node.js, allowing for a wide range of applications. Despite its limitations, such as security restrictions in browsers, JavaScript remains the most widely adopted language for creating interactive web interfaces and is supported by various transpiled languages that enhance its capabilities.

Uploaded by

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

Unit-4 (Java Script)

JavaScript is a versatile programming language primarily used for web development, enabling dynamic interaction with web pages through the ECMAScript, DOM, and BOM. It can run both client-side in web browsers and server-side using environments like Node.js, allowing for a wide range of applications. Despite its limitations, such as security restrictions in browsers, JavaScript remains the most widely adopted language for creating interactive web interfaces and is supported by various transpiled languages that enhance its capabilities.

Uploaded by

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

What is Java Script

JavaScript is a programming language initially designed to interact with elements of web pages.
In web browsers, JavaScript consists of three main parts:

 ECMAScript that provides the core functionality.

 The Document Object Model (DOM), which provides interfaces for interacting with
elements on web pages

 The Browser Object Model (BOM), which provides API for interacting with web
browsers.

JavaScript was initially created to “make web pages alive”.

The programs in this language are called scripts. They can be written right in a web page’s HTML
and run automatically as the page loads.

Scripts are provided and executed as plain text. They don’t need special preparation or
compilation to run.

In this aspect, JavaScript is very different from another language called Java.

When a web page is loaded i.e. after HTML and CSS have been downloaded, the JavaScript
engine in the web browser executes the JavaScript code. The JavaScript code then modifies the
HTML and CSS to dynamically update the user interface.

The JavaScript engine is a program that executes JavaScript code. However, modern JavaScript
engines are typically implemented as just-in-time compilers that compile JavaScript code to
bytecode for improved performance.

Client-side vs. Server-side JavaScript


When JavaScript is used on a web page, it is executed in the web browsers of user’s computers.
In this case, JavaScript works as a client-side language.

JavaScript can run on both web browsers and servers. A popular server-side environment for
JavaScript is [Link]. Unlike the client-side JavaScript, the server-side JavaScript executes on the
server that allows you to access databases, file systems, etc.
An Introduction to JavaScript
Let’s see what’s so special about JavaScript, what we can achieve with it, and what other
technologies play well with it.

What is JavaScript?

Why is it called JavaScript?

When JavaScript was created, it initially had another name: “LiveScript”. But Java was very
popular at that time, so it was decided that positioning a new language as a “younger brother”
of Java would help.

But as it evolved, JavaScript became a fully independent language with its own specification
called ECMAScript, and now it has no relation to Java at all.

Today, JavaScript can execute not only in the browser, but also on the server, or actually on any
device that has a special program called the JavaScript engine.

The browser has an embedded engine sometimes called a “JavaScript virtual machine”.

Different engines have different “codenames”. For example:

 V8 – in Chrome, Opera and Edge.

 SpiderMonkey – in Firefox.

 …There are other codenames like “Chakra” for IE, “JavaScriptCore”, “Nitro” and
“SquirrelFish” for Safari, etc.

The terms above are good to remember because they are used in developer articles on the
internet. We’ll use them too. For instance, if “a feature X is supported by V8”, then it probably
works in Chrome, Opera and Edge.

How do engines work?

Engines are complicated. But the basics are easy.

1. The engine (embedded if it’s a browser) reads (“parses”) the script.

2. Then it converts (“compiles”) the script to machine code.

3. And then the machine code runs, pretty fast.

The engine applies optimizations at each step of the process. It even watches the compiled
script as it runs, analyzes the data that flows through it, and further optimizes the machine code
based on that knowledge.
What can in-browser JavaScript do?

Modern JavaScript is a “safe” programming language. It does not provide low-level access to
memory or the CPU, because it was initially created for browsers which do not require it.

JavaScript’s capabilities greatly depend on the environment it’s running in. For
instance, [Link] supports functions that allow JavaScript to read/write arbitrary files, perform
network requests, etc.

In-browser JavaScript can do everything related to webpage manipulation, interaction with the
user, and the webserver.

For instance, in-browser JavaScript is able to:

 Add new HTML to the page, change the existing content, modify styles.

 React to user actions, run on mouse clicks, pointer movements, key presses.

 Send requests over the network to remote servers, download and upload files (so-
called AJAX and COMET technologies).

 Get and set cookies, ask questions to the visitor, show messages.

 Remember the data on the client-side (“local storage”).

What CAN’T in-browser JavaScript do?

JavaScript’s abilities in the browser are limited to protect the user’s safety. The aim is to prevent
an evil webpage from accessing private information or harming the user’s data.

Examples of such restrictions include:

 JavaScript on a webpage may not read/write arbitrary files on the hard disk, copy them
or execute programs. It has no direct access to OS functions.

Modern browsers allow it to work with files, but the access is limited and only provided if the
user does certain actions, like “dropping” a file into a browser window or selecting it via
an <input> tag.

There are ways to interact with the camera/microphone and other devices, but they require a
user’s explicit permission. So a JavaScript-enabled page may not sneakily enable a web-camera,
observe the surroundings and send the information to the NSA.

 Different tabs/windows generally do not know about each other. Sometimes they do, for
example when one window uses JavaScript to open the other one. But even in this case,
JavaScript from one page may not access the other page if they come from different
sites (from a different domain, protocol or port).

This is called the “Same Origin Policy”. To work around that, both pages must agree for data
exchange and must contain special JavaScript code that handles it. This limitation is, again, for
the user’s safety. A page from [Link] which a user has opened must not be able to
access another browser tab with the URL [Link] for example, and steal information
from there.

 JavaScript can easily communicate over the net to the server where the current page
came from. But its ability to receive data from other sites/domains is crippled. Though
possible, it requires explicit agreement (expressed in HTTP headers) from the remote
side. Once again, that’s a safety limitation.

Such limitations do not exist if JavaScript is used outside of the browser, for example on a server.
Modern browsers also allow plugins/extensions which may ask for extended permissions.

What makes JavaScript unique?

There are at least three great things about JavaScript:

 Full integration with HTML/CSS.

 Simple things are done simply.

 Supported by all major browsers and enabled by default.

JavaScript is the only browser technology that combines these three things.

That’s what makes JavaScript unique. That’s why it’s the most widespread tool for creating
browser interfaces.

That said, JavaScript can be used to create servers, mobile applications, etc.

Languages “over” JavaScript

The syntax of JavaScript does not suit everyone’s needs. Different people want different
features.

That’s to be expected, because projects and requirements are different for everyone.

So, recently a plethora of new languages appeared, which are transpiled (converted) to
JavaScript before they run in the browser.

Modern tools make the transpilation very fast and transparent, actually allowing developers to
code in another language and auto-converting it “under the hood”.
Examples of such languages:

 CoffeeScript is “syntactic sugar” for JavaScript. It introduces shorter syntax, allowing us


to write clearer and more precise code. Usually, Ruby devs like it.

 TypeScript is concentrated on adding “strict data typing” to simplify the development


and support of complex systems. It is developed by Microsoft.

 Flow also adds data typing, but in a different way. Developed by Facebook.

 Dart is a standalone language that has its own engine that runs in non-browser
environments (like mobile apps), but also can be transpiled to JavaScript. Developed by
Google.

 Brython is a Python transpiler to JavaScript that enables the writing of applications in


pure Python without JavaScript.

 Kotlin is a modern, concise and safe programming language that can target the browser
or Node.

There are more. Of course, even if we use one of these transpiled languages, we should also
know JavaScript to really understand what we’re doing.

Summary

 JavaScript was initially created as a browser-only language, but it is now used in many
other environments as well.

 Today, JavaScript has a unique position as the most widely-adopted browser language,
fully integrated with HTML/CSS.

 There are many languages that get “transpiled” to JavaScript and provide certain
features. It is recommended to take a look at them, at least briefly, after mastering
JavaScript.
History of JavaScript
JavaScript is developed by Brendan Eich, a computer scientist and programmer at Netscape
Communications Corporation. The initial name of the JavaScript was the 'Mocha'. After that, it
changed to 'LiveScript', and then 'JavaScript'. The 14th version, was released in June 2023.

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.

The Popular client-side libraries for JavaScript development are ReactJS, NextJS, Vue JS, Angular
JS, etc.

Server-Side JavaScript
In the early days, JavaScript was used for front-end development to add behaviors to HTML
pages. Since 2009, JavaScript is also used as a server-side programming language to build
scalable and dynamic web applications.

[Link] is one of the best and most popular JavaScript runtime environments for building the
server of applications using JavaScript. Using [Link], we can execute the JavaScript code
outside the browser and manage the server task. The server tasks can be an interaction with the
database, APIS, file handling, or maybe network communication. Due to the event-driven
architecture of [Link], it is faster than other server-side programming languages.
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 reasons.

 JavaScript cannot be used for networking applications because no such support is


available.

 JavaScript doesn't have any multi-threading capabilities.

Once again, JavaScript is a lightweight, interpreted programming language that allows you to
build interactivity into otherwise static HTML pages.

Imperative vs. Declarative JavaScript


JavaScript supports both imperative and declarative programming styles:

 Imperative Programming: Focuses on how to perform tasks by controlling the flow of


computation. This includes approaches like procedural and object-oriented
programming, often using constructs like async/await to handle asynchronous actions.

 Declarative Programming: Focuses on what should be done rather than how it’s done. It
emphasizes describing the desired result, such as with arrow functions, without detailing
the steps to achieve it.
JavaScript Development Tools
One of the major strengths of JavaScript is that it does not require expensive development
tools. You can start with a simple text editor such as Notepad. Since it is an interpreted language
inside the context of a web browser, you don't even need to buy a compiler.

Here are various free tools which can be helpful while developing applications with JavaScript.

 Visual Studio Code (VS Code) − The VS Code is a code editor used by most developers to
write JavaScript code. It is feature rich and contains various extensions that can increase
the productivity of any developer.

 Chrome dev tools − Programmers may use the Chrome dev tools to debug the JavaScript
code. However, they can use the debugging tool of any browser as most browser comes
with it.

The above 2 tools increase the productivity of the developer for writing the code. Furthermore,
you may use other tools like Git for version controlling, Webpack to build your application, etc.

Where is JavaScript Today?


In 2015, the ES6 version of JavaScript was launched with significant enhancements, including
object-oriented concepts, anonymous functions, template literals, etc. In June 2023, the ES14
(ECMAScript 2023), the 14th version of JavaScript was launched.

JavaScript Placement in HTML File


There is flexibility to place JavaScript code anywhere in an HTML document. However, the most
preferred ways to include JavaScript in an HTML file are as follows −

 Script in <head>...</head> section.

 Script in <body>...</body> section.

 Script in <body>...</body> and <head>...</head> sections.

 Script in an external file and then include in <head>...</head> section.

You can follow the syntax below to add JavaScript code using the script tag.

<script>

// JavaScript code

</script>
In the following section, we will see how we can place JavaScript in an HTML file in different
ways.

JavaScript in <head>...</head> section


If you want to have a script run on some event, such as when a user clicks somewhere,then you
will place that script in the head as follows −

<html>

<head>

<script type = "text/javascript">

function sayHello() {

alert("Hello World")

</script>

</head>

<body>

<input type = "button" value = "Say Hello" />

</body>

</html>

JavaScript in <body>...</body> section


If you need a script to run as the page loads so that the script generates content in the page,
then the script goes in the <body> portion of the document. In this case, youwould not have
any function defined using JavaScript. Take a look at the following code.

<html>

<head>

</head>

<body>

<script type = "text/javascript">


[Link]("Hello World")

</script>

<p>This is web page body </p>

</body>

</html>

JavaScript in <body> and <head> Sections


You can put your JavaScript code in <head> and <body> sections altogether as follows −

<html>

<head>

<script type = "text/javascript">

function sayHello() {

alert("Hello World")

</script>

</head>

<body>

<script type = "text/javascript">

[Link]("Hello World")

</script>

<input type = "button" value = "Say Hello" />

</body>

</html>

JavaScript in External File


As you begin to work more extensively with JavaScript, you will likely find cases where you are
reusing identical JavaScript code on multiple pages of a site.
You are not restricted to be maintaining identical code in multiple HTML files. The script tag
provides a mechanism to allow you to store JavaScript in an external file and then include it in
your HTML files.

To use JavaScript from an external file source, you need to write all your JavaScript source code
in a simple text file with the extension ".js" and then include that file as shown below.

For example, you can keep the following content in the [Link] file, and then you can use
the sayHello function in your HTML file after including the [Link] file.

[Link]

function sayHello() {

alert("Hello World")

External JavaScript file doesnt contain the <script> tag.

Here is an example to show how you can include an external JavaScript file in your HTML code
using the script tag and its src attribute.

You may include the external script reference within the <head> or <body> tag.

<html>

<head>

<script type = "text/javascript" src = "[Link]" ></script>

</head>

<body>

...

</body>

</html>

Also, you can create different modules to maintain code better and import each module in
another JavaScript file or import all modules in a single HTML file.

You can follow the below code to add multiple scripts into a single HTML file.

<head>

<script src = "[Link]" ></script>


<script src = "[Link]" ></script>

<script src = "[Link]" ></script>

</head>

External References
You can add an external JavaScript file in the HTML using the below 3 ways.

1. Using the full file path

When you need to add any hosted JavaScript file or a file that doesnt exists in the same project
into the HTML, you should use the full file path.

For example,

<head>

<script src = "C://javascript/[Link]" ></script>

</head>

2. Using the relative file path

If you are working on the project and JavaScript and HTML both files are in different folders, you
can use the relative file path.

<head>

<script src = "javascript\[Link]" ></script>

</head>

3. Using the filename only

If HTML and JavaScript both files are in the same folder, you can use the file name.

<head>

<script src = "[Link]" ></script>

</head>

Advantages of using the <script> tag


Here are the advantages of using the <script> tag to add JavaScript in the HTML.

Ease of Integration
The <script> tag allows developers to integrate JavaScript into the HTML file easily. Adding
JavaScript to the HTML file allows you to add behavior and interactivity to the web page.

Immediate Execution

Whenever the browser finds a <script> tag on the web page, it immediately executes the
JavaScript code defined inside that. It enables website visitors to interact with the web pages
and get real-time updates immediately.

Inline and External scripts

You can use the <script> tag to add the inline or external script into the HTML file. If you want to
load JavaScript before the HTML of a web page, you can add the <script. Tag in the <head> tag.
Otherwise, you can add the <script> tag in the <body> tag.

External Libraries and Frameworks integration

The <script> tag enables you to add external libraries and frameworks to the HTML web page.

For example, in the below code, we have added JQuery to the web page using its CDN.

<script src="[Link] </script>

Here, the "src" attribute contains the hosted link to the library.

Global Scope Access

Whatever code you define in the script tag has access to the global scope of the web page. You
can access the global variables, functions, etc., anywhere in the code.
JavaScript Object Definitions
Methods for Defining JavaScript Objects
 Using an Object Literal

 Using the new Keyword

 Using an Object Constructor

 Using [Link]()

 Using [Link]()

 Using [Link]()

Using an Object Literal

An object literal is a list of property key:values inside curly braces { }.

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

Example

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

Using the new Keyword

Example

// Create an Object
const person = new Object({
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
});

Note:

The examples above do exactly the same.

But, there is no need to use new Object().

For readability, simplicity and execution speed, use the object literal method.

Objects written as name value pairs are similar to:

 Associative arrays in PHP

 Dictionaries in Python

 Hash tables in C

 Hash maps in Java

 Hashes in Ruby and Perl

JavaScript [Link]()

The [Link]() method creates an object from an existing object.

Example

// Create an Object:
const person = {
firstName: "John",
lastName: "Doe"
};

// Create new Object


const man = [Link](person);
[Link] = "Peter";
JavaScript Object fromEntries()

ES2019 added the Object method fromEntries() to JavaScript.

The fromEntries() method creates an object from iterable key / value pairs.

Example

const fruits = [
["apples", 300],
["pears", 900],
["bananas", 500]
];

const myObj = [Link](fruits);

Browser Support

fromEntries() is an ECMAScript 2019 feature.

ES2019 is supported in all modern browsers since January 2020:

Chrome Edge Firefox Safari Opera


66 79 61 12 50

Apr 2018 Jan 2020 Jun 2018 Sep 2018 May 2018

JavaScript [Link]()

The [Link]() method copies properties from one or more source objects to a target
object.

Example

// Create Target Object


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

// Create Source Object


const person2 = {firstName: "Anne",lastName: "Smith"};

// Assign Source to Target


[Link](person1, person2);

In JavaScript, Objects are King.

If you Understand Objects, you Understand JavaScript.

In JavaScript, almost "everything" is an object.

 Objects are objects

 Maths are objects

 Functions are objects

 Dates are objects

 Arrays are objects

 Maps are objects

 Sets are objects

All JavaScript values, except primitives, are objects.

JavaScript Primitives
A primitive data type is data type that can only store a single primitive value.

JavaScript defines 7 types of primitive data types:

Type Example value

string "Hello"
number 3.14

boolean true

bigint 12345678901234

null null

undefined undefined

symbol symbol

Immutable

Primitive values are immutable (they are hardcoded and cannot be changed).

if x = 3.14, you can change the value of x, but you cannot change the value of 3.14.

Value Type Comment

"Hello" string "Hello" is always "Hello"

3.14 number 3.14 is always 3.14

true boolean true is always true

false boolean false is always false

null null null is always null

undefined undefined undefined is always undefined

JavaScript Objects are Mutable


Objects are mutable: They are addressed by reference, not by value.
If person is an object, the following statement will not create a copy of person:

const x = person;

The object x is not a copy of person. The object x is person.

The object x and the object person share the same memory address.

Any changes to x will also change person:

Example

//Create an Object
const person = {
firstName:"John",
lastName:"Doe",
age:50, eyeColor:"blue"
}

// Try to create a copy


const x = person;

// This will change age in person:


[Link] = 10;

JavaScript Objects
In JavaScript, an object is a fundamental, non-primitive data type used to store collections of
data and more complex entities. It represents a collection of properties, where each property
consists of a key (or property name) and a value.

Key Characteristics of JavaScript Objects:

 Key-Value Pairs:

Objects store data in key-value pairs. The key is always a string (or a symbol), and the value can
be any JavaScript data type, including primitives (strings, numbers, booleans, null, undefined),
other objects, or functions.
 Properties and Methods:

When a value in an object is a function, it is referred to as a method, representing an action or


behavior associated with the object. Other key-value pairs represent properties, which are the
data attributes of the object.

 Dynamic and Mutable:

Objects are dynamic, meaning properties can be added, modified, or deleted after the object
has been created. They are also mutable, allowing changes to their properties.

 Encapsulation:

Objects allow for the grouping and encapsulation of related data and behavior, making it easier
to manage and organize code.

Creating Objects:

Objects can be created using:

 Object Literal Syntax: This is the most common and concise way to create objects.

JavaScript

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

Object() Constructor.

JavaScript

const person = new Object();


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

Accessing and Modifying Properties:

Properties can be accessed and modified using: dot notation.

JavaScript

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


[Link] = "red";
 Bracket Notation: This is useful when property names contain special characters or are
dynamically determined.

JavaScript

[Link](car["model"]); // Output: 500


car["color"] = "blue";

Example:

JavaScript

const user = {
name: "Alice",
age: 30,
greet: function() {
[Link]("Hello, my name is " + [Link]);
}
};

[Link]([Link]); // Accessing a property


[Link] = 31; // Modifying a property
[Link](); // Calling a method

JavaScript RegExp (Regular Expression)


A regular expression is a special sequence of characters that defines a search pattern, typically
used for pattern matching within text. It's often used for tasks such as validating email
addresses, phone numbers, or checking if a string contains certain patterns (like dates, specific
words, etc.).

In JavaScript, RegExp is an object that is used to create regular expressions, which are patterns
used to match character combinations in strings.

// The /i flag makes the pattern case-insensitive

const patt = /Geeks/i;

const s1 = "geeksforgeeks";

const s2 = "forgeeks";
[Link]([Link](s1));

[Link]([Link](s2));

Output

true

true

Creating a RegExp in JavaScript

There are two primary ways to create a RegExp in JavaScript

1. Using the RegExp Constructor

The RegExp constructor is useful when you need to create a regular expression dynamically,
such as when the pattern or flags might change based on user input or other conditions.

let pattern = "hello"; // Pattern to match

let flags = "i"; // Case-insensitive flag

let regex = new RegExp(pattern, flags);

let s = "Hello world";

[Link]([Link](s));

Output

true

 Here, we dynamically create a RegExp object using the RegExp() constructor.

 The pattern "hello" will match the string "Hello" because of the 'i' flag, which makes the
search case-insensitive.

 [Link](s) returns true because "Hello" matches the pattern "hello" in a case-
insensitive manner.

2. Using Regular Expression Literal


This is the most common and simple way to create a regular expression in JavaScript. It’s
especially useful when the pattern is static (doesn’t change dynamically).

let regex = /hello/i;

let s = "Hello world";

[Link]([Link](s));

Output

true

 In this example, we define the regular expression directly using literal notation.

 /hello/i means we're looking for the word "hello", and the 'i' flag ensures the search is
case-insensitive.

 [Link](s) returns true because "Hello" matches the pattern "hello" case-insensitively.

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 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.


Metacharacter Description

\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

\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 quantitiesoccurrence

Quantifier Description

n+ Match any string that contains at least one n

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


Quantifier Description

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

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


Property Description

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

Use Cases of Regular Expressions

1. Validating Email Addresses

Regular expressions are frequently used for validating emails. Here’s an example that matches
most email formats

let regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;

[Link]([Link]("user@[Link]"));

Output

true

2. Extracting Specific Data from a String


You can use regular expressions to extract specific data from a string, like extracting all numbers
from a text.

let regex = /\d+/g;

let res = "There are 123 apples and 456 oranges".match(regex);

[Link](res);

Output

[ '123', '456' ]

3. Replacing Substrings

Regular expressions are often used in replacing certain substrings in text.

let regex = /foo/g;

let res = "foo bar foo".replace(regex, "baz");

[Link](res);

Output

baz bar baz

JavaScript Arrays
In JavaScript, an array is an ordered list of values. Each value, known as an element, is assigned
a numeric position in the array called its index. The indexing starts at 0, so the first element is at
position 0, the second at position 1, and so on.

Arrays can hold any type of data-such as numbers, strings, objects, or even other arrays—
making them a flexible and essential part of JavaScript programming.

Example:

If you have a list of items (a list of car names, for example), storing the cars in single variables
could look like this:
let car1 = "Saab"
let car2 = "Volvo"
let car3 ="BMW"

However, what if you want to loop through the cars and find a specific one? And what if you had
not 3 cars, but 300?

The solution is an array!

An array can hold many values under a single name, and you can access the values by referring
to an index number.

1. Create Array using Literal

Creating an array using array literal involves using square brackets [] to define and initialize the
array.

// Creating an Empty Array

let a = [];

[Link](a);

// Creating an Array and Initializing with Values

let b = [10, 20, 30];

[Link](b);

Output

[]

[ 10, 20, 30 ]

2. Create using new Keyword (Constructor)

The "Array Constructor" refers to a method of creating arrays by invoking the Array constructor
function.

// Creating and Initializing an array with values

let a = new Array(10, 20, 30);


[Link](a);

Output

[ 10, 20, 30 ]

Note: Both the above methods do exactly the same. Use the array literal method for efficiency,
readability, and speed.

Basic Operations on JavaScript Arrays

1. Accessing Elements of an Array

Any element in the array can be accessed using the index number. The index in the arrays starts
with 0.

// Creating an Array and Initializing with Values

let a = ["HTML", "CSS", "JS"];

// Accessing Array Elements

[Link](a[0]);

[Link](a[1]);

Output

HTML

CSS

2. Accessing the First Element of an Array

The array indexing starts from 0, so we can access first element of array using the index number.

// Creating an Array and Initializing with Values

let a = ["HTML", "CSS", "JS"];

// Accessing First Array Elements

let fst = a[0];


[Link]("First Item: ", fst);

Output

First Item: HTML

3. Accessing the Last Element of an Array

We can access the last array element using [[Link] - 1] index number.

// Creating an Array and Initializing with Values

let a = ["HTML", "CSS", "JS"];

// Accessing Last Array Elements

let lst = a[[Link] - 1];

[Link]("First Item: ", lst);

Output

First Item: JS

4. Modifying the Array Elements

Elements in an array can be modified by assigning a new value to their corresponding index.

// Creating an Array and Initializing with Values

let a = ["HTML", "CSS", "JS"];

[Link](a);

a[1]= "Bootstrap";

[Link](a);

Output
[ 'HTML', 'CSS', 'JS' ]

[ 'HTML', 'Bootstrap', 'JS' ]

5. Adding Elements to the Array

Elements can be added to the array using methods like push() and unshift().

 The push() method add the element to the end of the array.

 The unshift() method add the element to the starting of the array.

// Creating an Array and Initializing with Values

let a = ["HTML", "CSS", "JS"];

// Add Element to the end of Array

[Link]("[Link]");

// Add Element to the beginning

[Link]("Web Development");

[Link](a);

Output

[ 'Web Development', 'HTML', 'CSS', 'JS', '[Link]' ]

6. Removing Elements from an Array

To remove the elements from an array we have different methods like pop(), shift(), or splice().

 The pop() method removes an element from the last index of the array.

 The shift() method removes the element from the first index of the array.

 The splice() method removes or replaces the element from the array.

// Creating an Array and Initializing with Values

let a = ["HTML", "CSS", "JS"];


[Link]("Original Array: " + a);

// Removes and returns the last element

let lst = [Link]();

[Link]("After Removing the last: " + a);

// Removes and returns the first element

let fst = [Link]();

[Link]("After Removing the First: " + a);

// Removes 2 elements starting from index 1

[Link](1, 2);

[Link]("After Removing 2 elements starting from index 1: " + a);

Output

Original Array: HTML,CSS,JS

After Removing the last: HTML,CSS

After Removing the First: CSS

After Removing 2 elements starting from index 1: CSS

7. Array Length

We can get the length of the array using the array length property.

// Creating an Array and Initializing with Values

let a = ["HTML", "CSS", "JS"];

let len = [Link];


[Link]("Array Length: " + len);

Output

Array Length: 3

8. Increase and Decrease the Array Length

We can increase and decrease the array length using the JavaScript length property.

// Creating an Array and Initializing with Values

let a = ["HTML", "CSS", "JS"]

// Increase the array length to 7

[Link] = 7;

[Link]("After Increasing Length: ", a);

// Decrease the array length to 2

[Link] = 2;

[Link]("After Decreasing Length: ", a)

Output

After Increasing Length: [ 'HTML', 'CSS', 'JS', <4 empty items> ]

After Decreasing Length: [ 'HTML', 'CSS' ]

9. Iterating Through Array Elements

We can iterate array and access array elements using for loop and forEach loop.

Example: It is an example of for loop.

// Creating an Array and Initializing with Values

let a = ["HTML", "CSS", "JS"];


// Iterating through for loop

for (let i = 0; i < [Link]; i++) {

[Link](a[i])

Output

HTML

CSS

JS

Example: It is the example of [Link]() loop.

// Creating an Array and Initializing with Values

let a = ["HTML", "CSS", "JS"];

// Iterating through forEach loop

[Link](function myfunc(x) {

[Link](x);

});

Output

HTML

CSS

JS

10. Array Concatenation

Combine two or more arrays using the concat() method. It returns new array containing joined
arrays elements.

// Creating an Array and Initializing with Values

let a = ["HTML", "CSS", "JS", "React"];


let b = ["[Link]", "[Link]"];

// Concatenate both arrays

let concateArray = [Link](b);

[Link]("Concatenated Array: ", concateArray);

Output

Concatenated Array: [ 'HTML', 'CSS', 'JS', 'React', '[Link]', '[Link]' ]

11. Conversion of an Array to String

We have a builtin method toString() to converts an array to a string.

// Creating an Array and Initializing with Values

let a = ["HTML", "CSS", "JS"];

// Convert array ot String

[Link]([Link]());

Output

HTML,CSS,JS

12. Check the Type of an Arrays

The JavaScript typeof operator is used ot check the type of an array. It returns "object" for
arrays.

// Creating an Array and Initializing with Values

let a = ["HTML", "CSS", "JS"];

// Check type of array

[Link](typeof a);
Output

object

Recognizing a JavaScript Array

There are two methods by which we can recognize a JavaScript array:

 By using [Link]() method

 By using instanceof method

Below is an example showing both approaches:

const courses = ["HTML", "CSS", "Javascript"];

[Link]("Using [Link]() method: ", [Link](courses))

[Link]("Using instanceof method: ", courses instanceof Array)

Output

Using [Link]() method: true

Using instanceof method: true

Note: A common error is faced while writing the arrays:

const a = [5]
// and
const a = new Array(5)

The above two statements are not the same.

Output: This statement creates an array with an element " [5] ". Try with the following examples

// Example 1

const a1 = [5]

[Link](a1)

// Example 2

const a2 = new Array(5)


[Link](a2)

Output

[5]

[ <5 empty items> ]

You might also like