Unit 4 Notes
Unit 4 Notes
● 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.
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
Attribute Description
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>
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.
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
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.
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.
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.
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.
confirm() displays the confirm dialog box containing message with ok and cancel
button.
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.
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.
<script type="text/javascript">
function msg(){
alert("Hello Alert Box");
}
</script>
<input type="button" value="click" onclick="msg()"/>
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>
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()"/>
<script type="text/javascript">
function msg(){
open("http://www.javatpoint.com");
}
</script>
<input type="button" value="javatpoint" onclick="msg()"/>
<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.
String:
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)
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;
For example:
let price= 12.5;
let discount = 0.05;
● 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
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
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"
● The boolean type has two literal values: true and false in lowercase. The following
example declares two variables that hold the boolean values.
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.
● 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
Symbol:
● Different from other primitive types, the symbol type does not have a literal form.
● 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:
● 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
Variables are containers for storing data (storing data values) that can be changed later on.
Declare a Variable
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.
● 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;
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
● 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.
● 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.
function myfunction(){
let msg = "JavaScript!";
alert(greet + msg); //can access global and local variable
}
myfunction();
● 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.
myfunction();
alert(msg); // msg becomes global variable so can be accessed here
Points to Remember:
4.8 Hoisting
• 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.
• 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
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.
• 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.
• 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;
console.log(hoist);
const hoist = 'The variable has been hoisted.';
• The interpreter throws an error if we use a constant before declaring and initializing it.
const PI;
console.log(PI);
PI=3.142;
• Therefore, a constant variable must be both declared and initialized before use.
Function Hoisting
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,
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;
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.
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)
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
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'.
Operators
Arithmetic Operators
Arithmetic operators are used to perform arithmetic calculations.
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Remainder x%y
** Exponentiation (Power) x ** y
Example Program:
<html>
<body>
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.
!= Not equal to: returns true if the operands are not equal x != y
Strict not equal to: true if the operands are equal but
!== x !== y
of different type or not equal at all
Less than: true if the left operand is less than the right
< x<y
operand
Example Program:
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
Logical Operators
Logical operators perform logical operations and return a boolean value, either true or false.
Bitwise Operators
Bitwise operators perform operations on binary representations of numbers.
Operator Description
| Bitwise OR
^ Bitwise XOR
~ Bitwise NOT
<html>
<body>
<script type = "text/javascript">
<!--
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11
var linebreak = "<br />";
= 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
<html>
<body>
<script type = "text/javascript">
<!--
var a = 33;
var b = 10;
var linebreak = "<br />";
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.
Example:
let a = 5, b = "Hello ", c = "World!", d = 10;
a + d; //returns 15
<!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>
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 strict check means it will check datatype as well.
2. alert("Both are equal");
3. else
4. alert("Both are not 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.
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.
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
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
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>
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!
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
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.
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
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
Here, you need to create instance of array by passing arguments in constructor so that we don't
have to provide value explicitly.
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.
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.
Output:
"1BHK cost= 25000"
"Cost of 1BHK = 25000"
"Is house for rent = true"
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.
Output:
"1BHK"
25000
"2BHK"
50000
"Rent"
True
// same as fruits[fruits.length-1]
alert( fruits.at(-1) ); // Plum
pop
Extracts the last element of the array and returns it:
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:
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:
<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;
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
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"];
document.getElementById("demo").innerHTML = text;
function myFunction(value) {
text += "<li>" + value + "</li>";
}
</script>
</body>
</html>
Output:
JavaScript Arrays
Note:
JavaScript does not support arrays with named indexes.
In JavaScript, arrays always use numbered indexes.
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.
flatMap() It maps all array elements via mapping function, then flattens the result
into a new array.
from() It creates a new array carrying the exact copy of another array element.
filter() It returns the new array containing the elements that pass the provided
function conditions.
find() It returns the value of the first element in the given array that satisfies the
specified condition.
findIndex() It returns the index value of the first element in the given array that
satisfies the specified condition.
forEach() It invokes the provided function once for each element of an array.
includes() It checks whether the given array contains the specified element.
indexOf() It searches the specified element in the given array and returns the index
of the first match.
isArray() It tests if the passed value ia an array.
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.
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.
slice() It returns a new array containing the copy of the part of the given array.
toString() It converts the elements of a specified array into string form, without
affecting the original array.
unshift() It adds one or more elements in the beginning of the given array.
values() It creates a new iterator object carrying values for each index in the array.
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.
• When we iterate over the map object it returns the key, value pair in the same order
as inserted.
• //Example
let map1 = new Map();
map1.set('info', {name: 'Jack', age: 26});
console.log(map1);
Map Methods
Method Description
entries() Returns an iterator object with the [key, value] pairs in a Map
Property Description
Points to remember
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.
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
Output: 26
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.
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);
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
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:
Output:
Please visit W3Schools and Microsoft!
By default, the replace() method is case sensitive. Writing MICROSOFT (with upper-case)
will not work:
Output:
Please visit Microsoft!
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");
toUpperCase()
Output:
HELLO WORLD!
toLowerCase()
Output:
hello world!
concat()
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()
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()
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()
Output:
5xxx
Extracting String Characters
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()
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).
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.
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.
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);
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'.
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
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.
In the above example, an object student contains an object value in the marks property.
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;
}
};
Expressions Descriptions
Expressions Description
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
Property Description
Method Description
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!";
console.log(n);
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!";
console.log(txt);
}
myFunction();
Output:
Please visit geeksforgeeks!
// performing a replacement
const result1 = string.replace(/hello/, 'world');
console.log(result1); // Hello world hello
function 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
function validateEmail(email) {
// take input
let email = prompt('Enter an email: ');
validateEmail(email);
Output
Enter an email: hellohello
Enter a valid email: [email protected]
The email is valid.