Unit-4 (Java Script)
Unit-4 (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:
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.
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.
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?
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”.
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.
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.
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.
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.
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.
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.
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:
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.
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
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.
Once again, JavaScript is a lightweight, interpreted programming language that allows you to
build interactivity into otherwise static HTML pages.
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.
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.
<html>
<head>
function sayHello() {
alert("Hello World")
</script>
</head>
<body>
</body>
</html>
<html>
<head>
</head>
<body>
</script>
</body>
</html>
<html>
<head>
function sayHello() {
alert("Hello World")
</script>
</head>
<body>
[Link]("Hello World")
</script>
</body>
</html>
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")
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>
</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>
</head>
External References
You can add an external JavaScript file in the HTML using the below 3 ways.
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>
</head>
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>
</head>
If HTML and JavaScript both files are in the same folder, you can use the file name.
<head>
</head>
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.
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.
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.
Here, the "src" attribute contains the hosted link to the library.
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 [Link]()
Using [Link]()
Using [Link]()
Example
// Create an Object
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
Example
// Create an Object
const person = new Object({
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
});
Note:
For readability, simplicity and execution speed, use the object literal method.
Dictionaries in Python
Hash tables in C
JavaScript [Link]()
Example
// Create an Object:
const person = {
firstName: "John",
lastName: "Doe"
};
The fromEntries() method creates an object from iterable key / value pairs.
Example
const fruits = [
["apples", 300],
["pears", 900],
["bananas", 500]
];
Browser Support
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
JavaScript Primitives
A primitive data type is data type that can only store a single primitive 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.
const x = person;
The object x and the object person share the same memory address.
Example
//Create an Object
const person = {
firstName:"John",
lastName:"Doe",
age:50, eyeColor:"blue"
}
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-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:
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:
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
JavaScript
JavaScript
Example:
JavaScript
const user = {
name: "Alice",
age: 30,
greet: function() {
[Link]("Hello, my name is " + [Link]);
}
};
In JavaScript, RegExp is an object that is used to create regular expressions, which are patterns
used to match character combinations in strings.
const s1 = "geeksforgeeks";
const s2 = "forgeeks";
[Link]([Link](s1));
[Link]([Link](s2));
Output
true
true
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.
[Link]([Link](s));
Output
true
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.
[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
Metacharacter Description
\d Find a digit
\uxxxx Find the Unicode character specified by the hexadecimal number xxxxx
Quantifier Description
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 is not followed by a specific string m.
Property Description
constructor Return the function that created the RegExp object’s prototype
Method Description
Regular expressions are frequently used for validating emails. Here’s an example that matches
most email formats
[Link]([Link]("user@[Link]"));
Output
true
[Link](res);
Output
[ '123', '456' ]
3. Replacing Substrings
[Link](res);
Output
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?
An array can hold many values under a single name, and you can access the values by referring
to an index number.
Creating an array using array literal involves using square brackets [] to define and initialize the
array.
let a = [];
[Link](a);
[Link](b);
Output
[]
[ 10, 20, 30 ]
The "Array Constructor" refers to a method of creating arrays by invoking the Array constructor
function.
Output
[ 10, 20, 30 ]
Note: Both the above methods do exactly the same. Use the array literal method for efficiency,
readability, and speed.
Any element in the array can be accessed using the index number. The index in the arrays starts
with 0.
[Link](a[0]);
[Link](a[1]);
Output
HTML
CSS
The array indexing starts from 0, so we can access first element of array using the index number.
Output
We can access the last array element using [[Link] - 1] index number.
Output
First Item: JS
Elements in an array can be modified by assigning a new value to their corresponding index.
[Link](a);
a[1]= "Bootstrap";
[Link](a);
Output
[ 'HTML', 'CSS', 'JS' ]
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.
[Link]("[Link]");
[Link]("Web Development");
[Link](a);
Output
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.
[Link](1, 2);
Output
7. Array Length
We can get the length of the array using the array length property.
Output
Array Length: 3
We can increase and decrease the array length using the JavaScript length property.
[Link] = 7;
[Link] = 2;
Output
We can iterate array and access array elements using for loop and forEach loop.
[Link](a[i])
Output
HTML
CSS
JS
[Link](function myfunc(x) {
[Link](x);
});
Output
HTML
CSS
JS
Combine two or more arrays using the concat() method. It returns new array containing joined
arrays elements.
Output
[Link]([Link]());
Output
HTML,CSS,JS
The JavaScript typeof operator is used ot check the type of an array. It returns "object" for
arrays.
[Link](typeof a);
Output
object
Output
const a = [5]
// and
const a = new Array(5)
Output: This statement creates an array with an element " [5] ". Try with the following examples
// Example 1
const a1 = [5]
[Link](a1)
// Example 2
Output
[5]