Download as pdf or txt
Download as pdf or txt
You are on page 1of 53

WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

UNIT III
Introduction to javaScript

JavaScript is a lightweight, cross-platform, single-threaded, and interpreted


compiled programming language. It is also known as the scripting language for webpages.
It is well-known for the development of web pages, and many non-browser environments
also use it.
JavaScript is a weakly typed language (dynamically typed). JavaScript can be used
for Client-side developments as well as Server-side developments. JavaScript is both an
imperative and declarative type of language. JavaScript contains a standard library of
objects, like Array, Date, and Math, and a core set of language elements
like operators, control structures, and statements.

JavaScript can be added to HTML file in two ways:


 Internal JS: We can add JavaScript directly to our HTML file by writing the code inside
the <script> tag. The <script> tag can either be placed inside the <head> or the <body>
tag according to the requirement.
 External JS: We can write JavaScript code in another files having an extension.js and
then link this file inside the <head> tag of the HTML file in which we want to add this
code.
Syntax:
<script>
// JavaScript Code
</script>

Features of JavaScript
According to a recent survey conducted by Stack Overflow, JavaScript is the most popular
language on earth.With advances in browser technology and JavaScript having moved into
the server with Node.js and other frameworks, JavaScript is capable of so much more. Here
are a few things that we can do with JavaScript:
 JavaScript was created in the first place for DOM manipulation. Earlier websites were
mostly static, after JS was created dynamic Web sites were made.
 Functions in JS are objects. They may have properties and methods just like other
objects. They can be passed as arguments in other functions.
 Can handle date and time.
 Performs Form Validation although the forms are created using HTML.
 No compiler is needed.

Applications of JavaScript
 Web Development: Adding interactivity and behavior to static sites JavaScript was
invented to do this in 1995. By using AngularJS that can be achieved so easily.

NANDINI S D, GFGCW, H N PURA Page 1


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

 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. The Electron and
React are helpful in this department.
 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 for leisure.
The combination of JavaScript and HTML 5 makes JavaScript popular in game
development as well. It provides the EaseJS library which provides solutions for
working with rich graphics.
 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 their functioning.
 Art: Artists and designers can create whatever they want using JavaScript to draw on
HTML 5 canvas, and make the sound more effective also can be used p5.js library.
 Machine Learning: This JavaScript ml5.js library can be used in web development by
using machine learning.
 Mobile Applications: JavaScript can also be used to build an application for non-web
contexts. The features and uses of JavaScript make it a powerful tool for creating
mobile applications. This is a Framework for building web and mobile apps using
JavaScript. Using React Native, we can build mobile applications for different operating
systems. We do not require to write code for different systems. Write once use it
anywhere!

Limitations of JavaScript
 Security risks: JavaScript can be used to fetch data using AJAX or by manipulating
tags that load data such as <img>, <object>, <script>. These attacks are called cross-site
script attacks. They inject JS that is not part of the site into the visitor’s browser thus
fetching the details.
 Performance: JavaScript does not provide the same level of performance as offered by
many traditional languages as a complex program written in JavaScript would be
comparatively slow. But as JavaScript is used to perform simple tasks in a browser, so
performance is not considered a big restriction in its use.
 Complexity: To master a scripting language, programmers must have a thorough
knowledge of all the programming concepts, core language objects, and client and
server-side objects otherwise it would be difficult for them to write advanced scripts
using JavaScript.
 Weak error handling and type checking facilities: It is a weakly typed language as there
is no need to specify the data type of the variable. So wrong type checking is not
performed by compile.

NANDINI S D, GFGCW, H N PURA Page 2


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

Variables and Datatypes in JavaScript

Variables
In JavaScript, variables are used to store and manage data. They are created using
the var, let, or const keyword.
var:
Declares a variable. It has a function-scoped or globally-scoped behavior.
var x = 10;

Example: In this example, we will declare variables using var.


var a = "Hello GFGC"
var b = 10;
var c = 12;
var d = b + c;
console.log(a);
console.log(b);
console.log(c);
console.log(d);

output:
Hello GFGC
10
12
22

Block-scoped variables
It’s commonly used for variables that may change their value.
let y = "Hello";

Example: In this example, we will declare variables using let.


let a = "Hello learners"
let b = "joining";
let c = " 12";
let d = b + c;
console.log(a);
console.log(b);
console.log(c);
console.log(d);

Output
Hello learners
joining
12

NANDINI S D, GFGCW, H N PURA Page 3


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

joining 12

const:
Declares variables that cannot be reassigned. It’s block-scoped as well.
const PI = 3.14;

Example: In this example, we will declare the variable using the const keyword.
const a = "Hello learners"
console.log(a);
const b = 400;
console.log(b);
const c = "12";
console.log(c);

Output
Hello learners
400
12

Global Variable
These are variables that are defined in global scope i.e. outside of functions. These
variables have a global scope, so they can be accessed by any function directly. In the case
of global scope variables, the keyword they are declared with does not matter they all act
the same. A variable declared without a keyword is also considered global even though it is
declared in the function.

Local Variable
When you use JavaScript, local variables are variables that are defined within functions.
They have local scope, which means that they can only be used within the functions that
define them. Accessing them outside the function will throw an error

Data Types
JavaScript is a dynamically typed (also called loosely typed) scripting language. In
JavaScript, variables can receive different data types over time.
The latest ECMAScript standard defines eight data types Out of which seven data types
are Primitive(predefined) and one complex or Non-Primitive.

Primitive Data Types


The predefined data types provided by JavaScript language are known as primitive data
types. Primitive data types are also known as in-built data types.
 Number: JavaScript numbers are always stored in double-precision 64-bit binary format
IEEE 754. Unlike other programming languages, you don’t need int, float, etc to declare
different numeric values.

NANDINI S D, GFGCW, H N PURA Page 4


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

 String: JavaScript Strings are similar to sentences. They are made up of a list of
characters, which is essentially just an “array of characters, like “Hello GeeksforGeeks”
etc.
 Boolean: Represent a logical entity and can have two values: true or false.
 Null: This type has only one value that is null.
 Undefined: A variable that has not been assigned a value is undefined.
 Symbol: Symbols return unique identifiers that can be used to add unique property keys
to an object that won’t collide with keys of any other code that might add to the object.
 BigInt: BigInt is a built-in object in JavaScript that provides a way to represent whole
numbers larger than 253-1.

Non-Primitive Data Types


The data types that are derived from primitive data types of the JavaScript language are
known as non-primitive data types. It is also known as derived data types or reference data
types.
Object: It is the most important data type and forms the building blocks for modern
JavaScript. We will learn about these data types in detail in further articles.

“This course was packed with amazing and well-organized content! The project-based
approach of this course made it even better to understand concepts faster. Also the
instructor in the live classes is really good and knowledgeable.”- Tejas | Deutsche Bank

With our revamped Full Stack Development Program: master Node.js and React that
enables you to create dynamic web applications.
So get ready for salary hike only with our Full Stack Development Course.

JavaScript Operators
JavaScript operators operate the operands, these are symbols that are used to manipulate a
certain value or operand. Operators are used to performing specific mathematical and
logical computations on operands.

JavaScript Operators: There are various operators supported by JavaScript.

JavaScript Arithmetic Operators

Name Description Syntax

Addition ‘+’ operator performs Y = “GFGCW” + “for”


addition on two operands. This ‘+’ + “GFGCW” gives Y =
Addition (+)
operator can also be used to “GFGCW for GFGCW”
concatenate (add) strings. Y

NANDINI S D, GFGCW, H N PURA Page 5


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

Name Description Syntax

Subtraction ‘-‘ operator performs


Subtraction (-) Y = 5 – 3 gives Y = 2
subtraction on two operands.

Multiplication Multiplication ‘*’ operator performs


Y = 5 * 5 gives Y = 25
(*) multiplication on two operands.

Division ‘/’ operator performs division


Division (/) on two operands (divide the numerator Y = 5 / 5 gives Y = 1
by the denominator).

A % B means remainder
Modulus ‘%’ operator gives a
Modulus (%) (A/B) Y = 5 % 4 gives
remainder of an integer division.
Y=1

Exponentiation ‘**’ operator give the


Exponentiation Y = 5 ** 3 gives Y =
power of the first operator raised to the
(**) 125
second operator.

Increment ‘+ +’ operator increases an let A = 10 and Y = A +


Increment(++)
integer value by one. + then A = 11, Y=10

Decrement ‘- -‘ operator decreases an let A = 10 and Y = A –


Decrement (- -)
integer value by one. – then A = 9, Y=10

Unary (+) Unary ‘+’ is the fastest and preferred


+a means a is a positive
way of converting something into a
number
number

Negation ‘-‘ operator gives the -a means a is a negative


Negation (-)
negation of an operand. number

JavaScript Assignment Operators


The assignment operation evaluates the assigned value. Chaining the assignment operator
is possible in order to assign a single value to multiple variables

Name Description Syntax

NANDINI S D, GFGCW, H N PURA Page 6


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

Name Description Syntax

This operator assigns the right If A = 10 and Y = A


Assignment (=)
operand value to the left operand. then Y = 10

Addition Sums up left and right operand


Y += 1 gives Y = Y +
Assignment (+=) values and then assigns the result to
1
the left operand.

It subtracts the right side value from


Subtraction Y -= 1 gives Y = Y –
the left side value and then assigns
Assignment (- =) 1
the result to the left operand.

It multiplies a variable by the value


Multiplication Y *= A is equivalent
of the right operand and assigns the
Assignment (*=) to Y = Y * A
result to the variable.

It divides a variable by the value of


Division Y /= A is equivalent
the right operand and assigns the
Assignment (/ =) to Y = Y / A
result to the variable.

It divides a variable by the value of


Modules/Remainder Y %= A is equivalent
the right operand and assigns the
Assignment (% =) to Y = Y % A
remainder to the variable.

Y **= A is
Exponentiation This raises the value of a variable to
equivalent to Y=Y **
Assignment (** =) the power of the right operand.
A

It moves the specified amount of bits Y <<= A is


Left Shift
to the left and assigns the result to equivalent to Y=Y
Assignment (<< =)
the variable. << A

Right Shift It moves the specified amount of bits Y >>= A is


Assignment (>> =) to the right and assigns the result to equivalent to Y = Y
the variable. >> A

Bitwise AND : It does a bitwise AND operation on Y &= b is equivalent


Assignment (& =) the operand, and assigns the result to to Y = Y & A

NANDINI S D, GFGCW, H N PURA Page 7


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

Name Description Syntax

the variable.

It does a bitwise OR operation on the


Bitwise OR Y |= A is equivalent
operand, and assigns the result to the
Assignment (| =) to Y= Y | A
variable.

It does a bitwise XOR operation on


Bitwise XOR Y ^= A is equivalent
the operand, and assigns the result to
Assignment (^ =) to Y= Y ^ A
the variable.

JavaScript Comparison Operators


Comparison operators are mainly used to perform the logical operations that determine the
equality or difference between the values.

Name Description Syntax

Compares the equality of two


Y = 5 and X = 6 Y = = X
Equality (==) operands. If equal then the condition
is false.
is true otherwise false.

Compares the equality of two


Strict equality operands with type. If both value and Y = 5 and X = ‘5’ Y = = =
(===) type are equal then the condition is X is false.
true otherwise false.

Inequality (!=) Compares inequality of two operands. let X = 10 then X ! = 11


True if operands are not equal. (ie., 10!=11) is true.

Compares the inequality of two


Strict operands with type. If both value and let X = 10 then X ! == ’10’
inequality(!==) type are equal then the condition is (ie., 10 !== ‘10’) is true.
true otherwise false.

This operator checks whether the left


let X = 10 then X > 11(ie.,
Greater than (>) side value is greater than the right
10 >11) is false.
side value. If yes then it returns true

NANDINI S D, GFGCW, H N PURA Page 8


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

otherwise it returns false.

This operator checks whether the left


side value is less than the right side let X = 10 then X < 11(ie.,
Less than (<)
value. If yes then it returns true 10<11) is true.
otherwise it returns false.

This operator checks whether the left


Greater than or side operand is greater than or equal let X = 10 then X > =
Equal to (> =) to the right side operand. If yes then it 11(ie., 10>=11) is false.
returns true otherwise it returns false.

This operator checks whether the left


side operand value is less than or
Less than or let X = 10 then X < =
equal to the right side operand value.
Equal to (<= ) 10(ie., 10<=10) is true.
If yes then it returns true otherwise it
returns false.

JavaScript Logical Operators


These operators are used to determine the logic between variables or values.

Name Description Syntax

It checks whether two operands are non-


Logical AND
zero (0, false, undefined, null, or “” are
(&&). Y = 5 and X = 6 Y
considered as zero), if yes then return the
&& X is 6.
last operand when evaluating from left to
right

It checks whether two operands are non-


zero (0, false, undefined, null, or “” is
Y = 5 and X = 0 Y ||
Logical OR (||) considered as zero), if yes then return the
X is 5.
first operand when evaluating from left
to right.

It reverses the boolean result of the Y = 5 and X = 0 ! (Y


Logical NOT (!)
operand (or condition). || X) is false.

JavaScript Bitwise Operators


NANDINI S D, GFGCW, H N PURA Page 9
WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

The bitwise operator in JavaScript is used to convert the number to a 32-bit binary number
and perform the bitwise operation. The number is converted back to the 64-bit number after
the result.
Name Description Syntax

The operator returns true only if


Bitwise AND(&) A = 0, B=1 A&B = 0
both the operands are true

The operator returns true even if


Bitwise OR(|) A = 0, B=1 A|B = 1
one of the operands is true

The operator returns true if both


Bitwise XOR(^) A = 0, B=1 A^B = 1
operators are distinct

This operator is used to invert


Bitwise NOT(~) A = 0 ~A = 1
the boolean value of the operand

In this two operators are used


where the first operand is the
Bitwise Left
number and the second operand A = 6, B=1 A<<B = 12
Shift(<<)
is the number of bits to shift to
the left.

In this two operators are used


where the first operand is the
Bitwise Right
number and the second operand A = 6, B=1 A>>B = 3
Shift(>>)
is the number of bits to shift to
the right.

It is same as a bitwise right shift


Zero Fill Right
the only difference is that A = 6, B=1 A>>>B = 3
Shift(>>>)
overflowing bits are discarded.

JavaScript Ternary Operators


The ternary operator has three operands. It is the simplified operator of if/else.

Name Description Syntax

NANDINI S D, GFGCW, H N PURA Page 10


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

Y = ? A : B If the condition is
Ternary It is like the short form of the if-
true then Y = A otherwise Y =
Operator(?): else condition.
B

JavaScript Comma Operators


Comma Operator (,) mainly evaluates its operands from left to right sequentially and
returns the value of the rightmost operand.

Name Description Syntax

When a comma operator is placed


in an expression, it executes each Expression1, Expression2,
comma operator (,)
expression and returns the Expression3, …so on
rightmost expression.

JavaScript Unary Operators


A unary operation is an operation with only one operand.

Name Description Syntax

It returns the operand type, The


possible types that exist in
JavaScript typeof javascript are undefined, Object, typeof variable
boolean, number, string, symbol,
and function.

delete object
This operator is more specifically // or
Delete used to delete JavaScript object delete object.property
properties. // or
delete object[‘property’]

JavaScript Relational Operators


JavaScript Relational operators are used to compare its operands and determine the
relationship between them. They return a Boolean value (true or false) based on the
comparison result.

NANDINI S D, GFGCW, H N PURA Page 11


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

Name Description Syntax

The in operator returns true if the specified propNameOrNumber


in
property is in the specified object. in objectName

objectName
The instanceof operator returns true if the
instanceof instanceof
specified object is of the specified object type.
objectType

JavaScript BigInt Operators


Most operators that can be used between numbers can be used between BigInt values as
well.

Name Description Syntax

It returns a new BigInt object that


BigInt BigInt(value);
represents the original value.

JavaScript String Operators

Name Description Syntax

It concatenates two string values together,


concatenation
returning another string that is the union of str1 + str2
operator (+)
the two operand strings.

Conditional Statements in JavaScript

JavaScript Conditional statements allow you to execute specific blocks of code based on
conditions. If the condition meets then a particular block of action will be executed
otherwise it will execute another block of action that satisfies that particular condition.
There are several methods that can be used to perform Conditional Statements in
JavaScript.
 if statement: Executes a block of code if a specified condition is true.
 else statement: Executes a block of code if the same condition of the preceding if
statement is false.
 else if statement: Adds more conditions to the if statement, allowing for multiple
alternative conditions to be tested.

NANDINI S D, GFGCW, H N PURA Page 12


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

 switch statement: Evaluates an expression, then executes the case statement that
matches the expression’s value.
 ternary operator (conditional operator): Provides a concise way to write if-else
statements in a single line.

JavaScript Conditional statements Examples:

1. Using if Statement
The if statement is used to evaluate a particular condition. If the condition holds true, the
associated code block is executed.

Syntax:
if ( condition ) {
// If the condition is met,
//code will get executed.
}

Example: In this example, we are using the if statement to find given number is even or
odd.
let num = 20;
if (num % 2 === 0) {
console.log("Given number is even number.");
}
if (num % 2 !== 0) {
console.log("Given number is odd number.");
};

Output
Given number is even number.

2. Using if-else Statement


The if-else statement will perform some action for a specific condition. Here we are using
the else statement in which the else statement is written after the if statement and it has no
condition in their code block.

Syntax:
if (condition1) {
// Executes when condition1 is true
}
else
{
// Executes when condition2 is true
}

NANDINI S D, GFGCW, H N PURA Page 13


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

Example: In this example, we are using if-else conditional statement to check the driving
licence eligibility date.

let age = 25;


if (age >= 18) {
console.log("You are eligible of driving licence")
} else {
console.log("You are not eligible for driving licence")
};

Output
You are eligible of driving licence

3. else if Statement
The else if statement in JavaScript allows handling multiple possible conditions and
outputs, evaluating more than two options based on whether the conditions are true or false.

Syntax:
if (1st condition) {
// Code for 1st condition
} else if (2nd condition) {
// ode for 2nd condition
} else if (3rd condition) {
// Code for 3rd condition
} else {
// ode that will execute if all
// above conditions are false
}

Example: In this example, we are using the above-explained approach.


const num = 0;
if (num > 0) {
console.log("Given number is positive.");
} else if (num < 0) {
console.log("Given number is negative.");
} else {
console.log("Given number is zero.");
};

Output
Given number is zero.

4. Using Switch Statement (JavaScript Switch Case)

NANDINI S D, GFGCW, H N PURA Page 14


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

As the number of conditions increases, you can use multiple else-if statements in
JavaScript. but when we dealing with many conditions, the switch statement may be a more
preferred option.
Syntax:
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
...
case valueN:
statementN;
break;
default:
statementDefault;
};

Example: In this example, we find a branch name Based on the student’s marks, this
switch statement assigns a specific engineering branch to the variable Branch. The output
displays the student’s branch name,
const marks = 85; case marks >= 60:
let Branch; Branch = "Electronics and
switch (true) { communication";
case marks >= 90: break;
Branch = "Computer science case marks >= 50:
engineering"; Branch = "Civil engineering";
break; break;
case marks >= 80: default:
Branch = "Mechanical engineering"; Branch = "Bio technology";
break; break;
case marks >= 70: }
Branch = "Chemical engineering"; console.log(`Student Branch name is :
break; ${Branch}`);

Output
Student Branch name is : Mechanical engineering

5. Using Ternary Operator ( ?: )


The conditional operator, also referred to as the ternary operator (?:), is a shortcut for
expressing conditional statements in JavaScript.

NANDINI S D, GFGCW, H N PURA Page 15


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

Syntax:
condition ? value if true : value if false

Example: In this example, we use the ternary operator to check if the user’s age is 18 or
older. It prints eligibility for voting based on the condition.

let age = 21;


const result = (age >= 18) ? "You are eligible to vote.": "You are not eligible to vote.";
console.log(result);

Output
You are eligible to vote.

JavaScript Loops

JavaScript Loops are powerful tools for performing repetitive tasks efficiently. Loops in
JavaScript execute a block of code again and again while the condition is true.
For example, suppose we want to print “Hello World” 5 times. This can be done using JS
Loop easily. In Loop, the statement needs to be written only once and the loop will be
executed 5 times as shown below:

for (let i = 0; i < 5; i++) { Hello World!


console.log("Hello World!"); Hello World!
} Hello World!
Output Hello World!
Hello World!

JavaScript for Loop


The JS for loop provides a concise way of writing the loop structure. The for loop contains
initialization, condition, and increment/decrement in one line thereby providing a shorter,
easy-to-debug structure of looping.

Syntax
for (initialization; testing condition; increment/decrement) {
statement(s)
}
Flowchart

NANDINI S D, GFGCW, H N PURA Page 16


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

 Initialization condition: It initializes the variable and mark the start of a for loop. An
already declared variable can be used or a variable can be declared, local to loop only.
 Test Condition: It is used for testing the exit condition of a for loop. It must return a
boolean value. It is also an Entry Control Loop as the condition is checked prior to the
execution of the loop statements.
 Statement execution: Once the condition is evaluated to be true, the statements in the
loop body are executed.
 Increment/ Decrement: It is used for updating the variable for the next iteration.
 Loop termination: When the condition becomes false, the loop terminates marking the
end of its life cycle.

Example
// JavaScript program to illustrate for loop
let x; Output
for (x = 2; x <= 4; x++) { Value of x: 2
console.log("Value of x: " + x); Value of x: 3
} Value of x: 4

JavaScript while Loop


The JS while loop is a control flow statement that allows code to be executed repeatedly
based on a given Boolean condition. The while loop can be thought of as a repeating if
statement.
Syntax
while (boolean condition) {
loop statements...
}

Flowchart

 While loop starts with checking the condition. If it is evaluated to be true, then the loop
body statements are executed otherwise first statement following the loop is executed.
For this reason, it is also called the Entry control loop
 Once the condition is evaluated to be true, the statements in the loop body are executed.
Normally the statements contain an updated value for the variable being processed for
the next iteration.
 When the condition becomes false, the loop terminates which marks the end of its life
cycle.

NANDINI S D, GFGCW, H N PURA Page 17


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

Example
// JavaScript code to use while loop
let val = 1; Output
while (val < 6) 1
{ 2
console.log(val); 3
val += 1; 4
} 5

JavaScript do-while Loop


The JS do-while loop is similar to the while loop with the only difference is that it checks
for the condition after executing the statements, and therefore is an example of an Exit
Control Loop. It executes loop content at least once event the condition is false.

Syntax
do {
Statements...
}
while (condition);

Flowchart

 The do-while loop starts with the execution of the statement(s). There is no checking of
any condition for the first time.
 After the execution of the statements and update of the variable value, the condition is
checked for a true or false value. If it is evaluated to be true, the next iteration of the
loop starts.
 When the condition becomes false, the loop terminates which marks the end of its life
cycle.
 It is important to note that the do-while loop will execute its statements at least once
before any condition is checked and therefore is an example of the exit control loop.
Example
let test = 1;
do { } while(test <= 5)
console.log(test);
test++; Output
NANDINI S D, GFGCW, H N PURA Page 18
WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

1 4
2 5
3

JavaScript for-in Loop


JS for-in loop is used to iterate over the properties of an object. The for-in loop iterates
only over those keys of an object which have their enumerable property set to “true”.

Syntax
for(let variable_name in object_name) {
// Statement
}

Example: This example shows the use of for-in loop.


let myObj = { x: 1, y: 2, z: 3 }; Output
for (let key in myObj) { x1
console.log(key, myObj[key]); y2
} z3

JavaScript for-of Loop


JS for-of loop is used to iterate the iterable objects for example – array, object, set and
map. It directly iterate the value of the given iterable object and has more concise syntax
than for loop.

Syntax:
for(let variable_name of object_name) {
// Statement
}

Example: This example shows the use of for-of loop.

let arr = [1, 2, 3, 4, 5]; 1


for (let value of arr) { 2
console.log(value); 3
} 4
5
Output

JavaScript Labeled Statement


JS label keyword does not include a goto keyword. Users can use the continue keyword
with the label statement. Furthermore, users can use the break keyword to terminate the
loop/block. You can also use the break keyword without defining the label but it terminates

NANDINI S D, GFGCW, H N PURA Page 19


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

only the parent loop/block. To terminate the outer loop from the inner loop using the break
keyword, users need to define the label.

Syntax
Label:
statement (loop or block of code)

Example
let sum = 0, a = 1; if (sum > 12) {
// Label for outer loop break outerloop;
outerloop: while (true) { }
a = 1; console.log("sum = " + sum);
// Label for inner loop a++;
innerloop: while (a < 3) { }
sum += a; }
sum = 6
Output sum = 7
sum = 1 sum = 9
sum = 3 sum = 10
sum = 4 sum = 12

JavaScript Break Statement


JS break statement is used to terminate the execution of the loop or switch statement when
the condition is true.

Syntax
break;

Example
for (let i = 1; i < 6; i++) {
if (i == 4) Output
break; 1
console.log(i); 2
} 3

JavaScript Continue Statement


JS continue statement is used to break the iteration of the loop and follow with the next
iteration. The break in iteration is possible only when the specified condition going to
occur. The major difference between the continue and break statement is that the break
statement breaks out of the loop completely while continue is used to break one statement
and iterate to the next statement.

Syntax
continue;
NANDINI S D, GFGCW, H N PURA Page 20
WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

Example
for (let i = 0; i < 11; i++) { Output
if (i % 2 == 0) 1
continue; 3
5
console.log(i); 7
} 9

Functions in JavaScript
JavaScript function is a set of statements that take inputs, do some specific computation,
and produce output.
A JavaScript function is executed when “something” invokes it (calls it).

Example: A basic javascript function, here we create a function that divides the 1st element
by the second element.
function myFunction(g1, g2) {
return g1 / g2;
}
const value = myFunction(8, 2); // Calling the function
console.log(value);

output:
4

You must already have seen some commonly used functions in JavaScript like alert(),
which is a built-in function in JavaScript. But JavaScript allows us to create user-defined
functions also. We can create functions in JavaScript using the keyword `function`.

Syntax: The basic syntax to create a function in JavaScript is shown below.


function functionName(Parameter1, Parameter2, ...)
{
// Function body
}
To create a function in JavaScript, we have to first use the keyword function, separated by
the name of the function and parameters within parenthesis. The part of the function inside
the curly braces {} is the body of the function.
In javascript, functions can be used in the same way as variables for assignments, or
calculations.

Function Invocation:
 Triggered by an event (e.g., a button click by a user).
 When explicitly called from JavaScript code.

NANDINI S D, GFGCW, H N PURA Page 21


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

 Automatically executed, such as in self-invoking functions.

Function Definition:
Before, using a user-defined function in JavaScript we have to create one. We can use the
above syntax to create a function in JavaScript. A function definition is sometimes also
termed a function declaration or function statement. Below are the rules for creating a
function in JavaScript:
 Every function should begin with the keyword function followed by,
 A user-defined function name that should be unique,
 A list of parameters enclosed within parentheses and separated by commas,
 A list of statements composing the body of the function enclosed within curly braces {}.

Example: This example shows a basic declaration of a function in javascript.


function calcAddition(number1, number2) {
return number1 + number2;
}
console.log(calcAddition(6,9));

Output
15

In the above example, we have created a function named calcAddition,


 This function accepts two numbers as parameters and returns the addition of these two
numbers.
 Accessing the function with just the function name without () will return the function
object instead of the function result.
There are three ways of writing a function in JavaScript:

Function Declaration: It declares a function with a function keyword. The function


declaration must have a function name.
Syntax:
function gfgcw(paramA, paramB) {
// Set of statements
}

Function Expression:
It is similar to a function declaration without the function name. Function expressions can
be stored in a variable assignment.
Syntax:
let gfgcw= function(paramA, paramB) {
// Set of statements
}

Example: This example explains the usage of the Function expression.


NANDINI S D, GFGCW, H N PURA Page 22
WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

const square = function (number) {


return number * number;
};
const x = square(4);
console.log(x);

Output
16

Functions as Variable Values


Functions can be used the same way as you use variables.

Example:
// Function to convert Fahrenheit to Celsius
function toCelsius(fahrenheit) {
return (fahrenheit - 32) * 5/9;
}

// Using the function to convert temperature


let temperatureInFahrenheit = 77;
let temperatureInCelsius = toCelsius(temperatureInFahrenheit);
let text = "The temperature is " + temperatureInCelsius + " Celsius";

Arrow Function:
It is one of the most used and efficient methods to create a function in JavaScript because
of its comparatively easy implementation. It is a simplified as well as a more compact
version of a regular or normal function expression or syntax.
Syntax:
let function_name = (argument1, argument2 ,..) => expression

Example: This example describes the usage of the Arrow function.


const a = ["Hydrogen", "Helium", "Lithium", "Beryllium"];
const a2 = a.map(function (s) {
return s.length; });
console.log("Normal way ", a2); // [8, 6, 7, 9]
const a3 = a.map((s) => s.length);
console.log("Using Arrow Function ", a3); // [8, 6, 7, 9]

Output
Normal way [ 8, 6, 7, 9 ]
Using Arrow Function [ 8, 6, 7, 9 ]

Function Parameters

NANDINI S D, GFGCW, H N PURA Page 23


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

Till now, we have heard a lot about function parameters but haven’t discussed them in
detail. Parameters are additional information passed to a function. For example, in the
above example, the task of the function calcAddition is to calculate the addition of two
numbers. These two numbers on which we want to perform the addition operation are
passed to this function as parameters. The parameters are passed to the function within
parentheses after the function name and separated by commas. A function in JavaScript can
have any number of parameters and also at the same time, a function in JavaScript can not
have a single parameter.

Example: In this example, we pass the argument to the function.


function multiply(a, b) {
b = typeof b !== "undefined" ? b : 1;
return a * b;
}
console.log(multiply(69));

Output
69

Calling Functions:
After defining a function, the next step is to call them to make use of the function. We can
call a function by using the function name separated by the value of parameters enclosed
between the parenthesis and a semicolon at the end. The below syntax shows how to call
functions in JavaScript:

Syntax:
functionName( Value1, Value2, ..);

Example: Below is a sample program that illustrates the working of functions in


JavaScript:
function welcomeMsg(name) {
return ("Hello " + name + " welcome to Gfgc");
}
let nameVal = "Admin";
console.log(welcomeMsg(nameVal));

Output:
Hello Admin welcome to Gfgc

Return Statement
There are some situations when we want to return some values from a function after
performing some operations. In such cases, we can make use of the return statement in
JavaScript. This is an optional statement and most of the time the last statement in a

NANDINI S D, GFGCW, H N PURA Page 24


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

JavaScript function. Look at our first example with the function named as calcAddition.
This function is calculating two numbers and then returns the result.

Syntax: The most basic syntax for using the return statement is:
return value;

The return statement begins with the keyword return separated by the value which we want
to return from it. We can use an expression also instead of directly returning the value.

How to write a function in JavaScript ?


A JavaScript function is a collection of reusable code that may be invoked from anywhere
in your application. This avoids the need to write the same code again and over. It aids
programmers in the creation of modular code. Functions enable a programmer to break
down a large program into several smaller and more manageable functions.
Functions are one of JavaScript’s core building elements. In JavaScript, a function is
comparable to a procedure—a series of words that performs a task or calculates a value—
but for a process to qualify as a function, it must accept some input and produce an output
with a clear link between the input and the result. To utilize a function, it must be defined
in some place within the scope from which it will be called.

Function Definition
A function definition or function statement starts with the function keyword and continues
with the following.
 Function’s name.
 A list of function arguments contained in parenthesis and separated by commas.
 Statements are enclosed in curly brackets.

Syntax:
function name(arguments)
{
javascript statements
}

Function Calling
To call a function at a later point in the script, simply type the function’s name. By default,
all JavaScript functions can utilize argument objects. Each parameter’s value is stored in an
argument object. The argument object is similar to an array. Its values may be accessed
using an index, much like an array. It does not, however, provide array methods.

function welcome() {
console.log("welcome to GfGC");
}
welcome();

NANDINI S D, GFGCW, H N PURA Page 25


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

Output
welcome to GfGC

Function Arguments
A function can contain one or more arguments that are sent by the calling code and can be
utilized within the function. Because JavaScript is a dynamically typed programming
language, a function argument can have any data type as a value.

function welcome(name) {
console.log("Hey " + "" + name + " " + "welcome to GfG");
}
// Passing arguments
welcome("Rohan");

Output
Hey Rohan welcome to GfGC

Return Value
A return statement is an optional part of a JavaScript function. If you wish to return a value
from a function, you must do this. This should be the final statement of a function.

function welcome() {
// Return statement
return "Welcome to GfGG";
}
console.log(welcome());

Output
Welcome to GfGC

Function Expression
We may assign a function to a variable and then utilize that variable as a function in
JavaScript. It is known as a function expression.

let welcome = function () {


return "Welcome to GfGC";
}
let gfgc = welcome();
console.log(gfgc);

Output
Welcome to GfGC

Types Of Functions in Javascript


NANDINI S D, GFGCW, H N PURA Page 26
WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

1. Named function:
A named function is one that we write in code and then use whenever we need it by
referencing its name and providing it with some parameters. Named functions come in
handy when we need to call a function several times to give various values to it or run it
multiple times.

function add(a, b) {
return a + b;
}
console.log(add(5, 4));

Output
9

2. Anonymous function:
We can define a function in JavaScript without giving it a name. This nameless function is
referred to as the anonymous function. A variable must be assigned to an anonymous
function.

let add = function (a, b) {


return a + b;
}
console.log(add(5, 4));

Output
9

3. Nested Functions:
A function in JavaScript can contain one or more inner functions. These nested functions
fall within the purview of the outer function. The inner function has access to the variables
and arguments of the outer function. However, variables declared within inner functions
cannot be accessed by outer functions.

function msg(firstName) {
function hey() {
console.log("Hey " + firstName);
}
return hey();
}
msg("Ravi");

Output
Hey Ravi

NANDINI S D, GFGCW, H N PURA Page 27


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

4. Immediately invoked function expression:


The browser executes the invoked function expression as soon as it detects it. This function
has the advantage of running instantly where it is situated in the code and producing direct
output. That is, it is unaffected by code that occurs later in the script and can be beneficial.

let msg = (function() {


return "Welcome to GfgC" ;
})();
console.log(msg);

Output
Welcome to GfgC

JavaScript Function Call


JavaScript function calls involve invoking a function to execute its code. You can call a
function by using its name followed by parentheses (), optionally passing arguments inside
the parentheses.

Syntax:
call()

Return Value: It calls and returns a method with the owner object being the argument.

JavaScript Function Call Examples


Example 1: This example demonstrates the use of the call() method.
// function that returns product of two numbers
function product(a, b) {
return a * b;
}
// Calling product() function
let result = product.call(this, 20, 5);
console.log(result);

Output
100

JavaScript Numbers
JavaScript Numbers are primitive data types. Unlike other programming languages, you
don’t need int, float, etc. to declare different numeric values. JavaScript numbers are
always stored in double-precision 64-bit binary format IEEE 754.
This format stores numbers in 64 bits,
 0-51 bit stores value(fraction)
 52-62 bit stores exponent

NANDINI S D, GFGCW, H N PURA Page 28


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

 63-bit stores sign

Numeric Types in JavaScript


In JavaScript, numbers play an important role, and understanding their behavior is essential
for effective programming. Let’s explore the various aspects of numeric types in
JavaScript.

1. The Only Numeric Type


As we know JavaScript has only one numeric type: the double-precision 64-bit binary
format IEEE 754 means that it doesn’t differentiate between integers and floating-point
numbers explicitly. Instead, it uses a unified approach for all numeric values. (f)
 Integers and floating-point numbers are both represented using this format.
 The numeric precision is 53 bits, allowing for an accurate representation of integer
values ranging from -2^53 + 1 to 2^53 – 1.

2. Scientific Notation
JavaScript allows writing extra-large or extra-small numbers using scientific (exponent)
notation.
Example:
let a = 156e5;
let b = 156e-5; Output
console.log(a); 15600000
console.log(b); 0.00156

3. Integer Precision
Integers (numbers without a period or exponent notation) are accurate up to 15 digits.

Example:
let a = 999999999999999;
let b = 9999999999999999; Output
console.log(a); 999999999999999
console.log(b); 10000000000000000

4. Floating Point Precision


Floating point arithmetic is not always 100% accurate due to binary representation
limitations.

Example:
let x = 0.22 + 0.12; //x will be let x = 0.22 + 0.12;
0.33999999999999997 let y = (0.22 * 10 + 0.12 * 10) / 10;
To solve this problem, multiply and console.log(x);
divide: console.log(y);
let x = (0.22 * 10 + 0.12 * 10) / 10; // x
will be 0.34 Output
NANDINI S D, GFGCW, H N PURA Page 29
WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

0.33999999999999997 0.34

5. Adding Numbers and Strings


 JavaScript uses the `+` operator for both addition and concatenation.
 Numbers are added, when strings are concatenated.

Example:
// Adding two numbers let b = "30";
let x = 10; let c = a + b;
let y = 15; console.log(c);
let z = x + y;
console.log(z); Output
// Concatenating two strings: 25
let a = "10"; 1030

6. Numeric Strings
JavaScript automatically converts the numeric strings to numbers in most operations like.

Example:
let x = "100" / "10";
let y = "100" * "10"; Output
let z = "100" - "10"; 10
console.log(x); 1000
console.log(y); 90
console.log(z);

Number Literals:
The types of number literals You can use decimal, binary, octal, and hexadecimal.
1. Decimal Numbers:
JavaScript Numbers does not have different types of numbers(ex: int, float, long, short)
which other programming languages do. It has only one type of number and it can hold
both with or without decimal values.

let a=33;
let b=3.3; Output
console.log(a); 33
console.log(b); 3.3

2. Octal Number:
If the number starts with 0 and the following number is smaller than 8. It will be parsed as
an Octal Number.
let x = 0562; Output
console.log(x); 370

NANDINI S D, GFGCW, H N PURA Page 30


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

3. Binary Numbers:
They start with 0b or 0B followed by 0’s and 1’s.

let x = 0b11;
let y = 0B0111; Output
console.log(x); 3
console.log(y); 7

4. Hexadecimal Numbers:
They start with 0x or 0X followed by any digit belonging (0123456789ABCDEF)

let x = 0xfff; Output


console.log(x); 4095

JavaScript Strings

What is String in JavaScript?


JavaScript String is a sequence of characters, typically used to represent text. It is
enclosed in single or double quotes and supports various methods for text manipulation.

You can create JavaScript Strings by enclosing text in single or double quotes. String
literals and the String constructor provide options. Strings allow dynamic manipulation,
making it easy to modify or extract elements as needed.

Basic Terminologies of JavaScript String


 String: A sequence of characters enclosed in single (‘ ‘) or double (” “) quotes.
 Length: The number of characters in a string, obtained using the length property.
 Index: The position of a character within a string, starting from 0.
 Concatenation: The process of combining two or more strings to create a new one.
 Substring: A portion of a string, obtained by extracting characters between specified
indices.

Declaration of a String

1. Using Single Quotes


Single Quotes can be used to create a string in JavaScript. Simply enclose your text within
single quotes to declare a string.
Syntax:
let str = 'String with single quote';

NANDINI S D, GFGCW, H N PURA Page 31


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

Example:
let str = 'Create String with Single Quote'; Output
console.log(str); Create String with Single Quote

2. Using Double Quotes


Double Quotes can also be used to create a string in JavaScript. Simply enclose your text
within double quotes to declare a string.

Syntax:
let str = “String with double quote”;

Example:
let str = "Create String with Double
Quote"; Output
console.log(str); Create String with Double Quote

3. String Constructor
You can create a string using the String Constructor. The String Constructor is less
common for direct string creation, it provides additional methods for manipulating strings.
Generally, using string literals is preferred for simplicity.

let str = new String('Create String with Output


String Constructor'); [String: 'Create String with String
console.log(str); Constructor']

4. Using Template Literals (String Interpolation)


You can create strings using Template Literals. Template literals allow you to embed
expressions within backticks (`) for dynamic string creation, making it more readable and
versatile.

Syntax:
let str = 'Template Litral String';
let newStr = `String created using ${str}`;

Example:
let str = 'Template Litral String';
let newStr = `String created using ${str}`; Output
console.log(newStr); String created using Template Litral String
5. Empty String
You can create an empty string by assigning either single or double quotes with no
characters in between.

Syntax:
NANDINI S D, GFGCW, H N PURA Page 32
WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

// Create Empty Strign with Single Quotes


let str1 = '';
// Create Empty Strign with Double Quotes
let str2 = "";

Example:
let str1 = '';
let str2 = ""; Output
console.log("Empty String with Single Empty String with Single Quotes:
Quotes: " + str1); Empty String with Double Quotes:
console.log("Empty String with Double
Quotes: " + str2);

6. Multiline Strings (ES6 and later)


You can create a multiline string using backticks (“) with template literals. The backticks
allows you to span the string across multiple lines, preserving the line breaks within the
string.

Syntax:
let str = `
This is a
multiline
string`;

Example:
let str = `
This is a Output
multiline This is a
string`; multiline
console.log(str); string

Basic Operations on JavaScript Strings

1. Finding the length of a String


You can find the length of a string using the length property.

Example: Finding the length of a string.


let str = 'JavaScript'; console.log("String Length: " + len);
let len = str.length;
console.log("String Length: " + len); Output
let str = 'JavaScript'; String Length: 10
let len = str.length;

NANDINI S D, GFGCW, H N PURA Page 33


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

2. String Concatenation
You can combine two or more strings using + Operator.

Example:
let str1 = 'Java';
let str2 = 'Script'; Output
let result = str1 + str2; Concatenated String: JavaScript
console.log("Concatenated String: " +
result);

3. Escape Characters
We can use escape characters in string to add single quotes, dual quotes, and backslash.

Syntax:
\' - Inserts a single quote
\" - Inserts a double quote
\\ - Inserts a backslash

Example: In this example we are using escape characters


const str1 = "\'GfG\' is a learning portal";
const str2 = "\"GfG\" is a learning portal"; Output
const str3 = "\\GfG\\ is a learning portal"; 'GfG' is a learning portal
console.log(str1); "GfG" is a learning portal
console.log(str2); \GfG\ is a learning portal
console.log(str3);

4. Breaking Long Strings


We will use a backslash to break a long string in multiple lines of code.

const str = "'GFGCW' is \ Output


a learning portal"; 'GFGCW' is a learning portal
console.log(str);

Note: This method might not be supported on all browsers.

Example: The better way to break a string is by using the string addition.
const str = "'GFGCW' is a"
+ " learning portal"; Output
console.log(str); 'GFGCW' ' is a learning portal

5. Find Substring of a String


We can extract a portion of a string using the substring() method.

NANDINI S D, GFGCW, H N PURA Page 34


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

let str = 'JavaScript Tutorial';


let substr = str.substring(0, 10); Output
console.log(substr); JavaScript

6. Convert String to Uppercase and Lowercase


Convert a string to uppercase and lowercase
using toUpperCase() and toLowerCase() methods.

let str = 'JavaScript';


let upperCase = str.toUpperCase(); Output
let lowerCase = str.toLowerCase(); JAVASCRIPT
console.log(upperCase); javascript
console.log(lowerCase);

7. String Search in JavaScript


Find the index of a substring within a string using indexOf() method.

let str = 'Learn JavaScript at GfG'; Output


let searchStr = str.indexOf('JavaScript'); 6
console.log(searchStr);

8. String Replace in JavaScript


Replace occurrences of a substring with another using replace() method.

let str = 'Learn HTML at GfG'; console.log(newStr);


let newStr = str.replace('HTML', Output
'JavaScript'); Learn JavaScript at GfG

9. Trimming Whitespace from String


Remove leading and trailing whitespaces using trim() method.

let str = ' Learn JavaScript ';


let newStr = str.trim(); Output
console.log(newStr); Learn JavaScript

10. Access Characters from String


Access individual characters in a string using bracket notation and charAt() method.

let str = 'Learn JavaScript'; console.log(charAtIndex);


let charAtIndex = str[6];
console.log(charAtIndex); Output
charAtIndex = str.charAt(6); J
J

NANDINI S D, GFGCW, H N PURA Page 35


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

11. String Comparison in JavaScript


There are some inbuilt methods that can be used to compare strings such as the equality
operator and another like localeCompare() method.

let str1 = "John";


let str2 = new String("John"); Output
console.log(str1 == str2); true
console.log(str1.localeCompare(str2)); 0

12. Passing JavaScript String as Objects


We can create a JavaScript string using the new keyword.

const str = new String("GFGCW"); Output


console.log(str); [String: 'GFGCW']
JavaScript Arrays
Array in JavaScript
JavaScript Array is a data structure that allows you to store and organize multiple values
within a single variable. It is a versatile and dynamic object. It can hold various data types,
including numbers, strings, objects, and even other arrays. Arrays in JavaScript are zero-
indexed i.e. the first element is accessed with an index 0, the second element with an index
of 1, and so forth.

You can create JavaScript Arrays using the Array constructor or using the shorthand array
literal syntax, which employs square brackets. Arrays can dynamically grow or shrink in
size as elements are added or removed.

Basic Terminologies of JavaScript Array


 Array: A data structure in JavaScript that allows you to store multiple values in a single
variable.
 Array Element: Each value within an array is called an element. Elements are accessed
by their index.
 Array Index: A numeric representation that indicates the position of an element in the
array. JavaScript arrays are zero-indexed, meaning the first element is at index 0.
 Array Length: The number of elements in an array. It can be retrieved using the length
property.

Declaration of an Array

NANDINI S D, GFGCW, H N PURA Page 36


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

There are basically two ways to declare an array i.e. Array Literal and Array Constructor.
1. Creating an Array using Array Literal
Creating an array using array literal involves using square brackets [] to define and
initialize the array. This method is concise and widely preferred for its simplicity.

Syntax:
let arrayName = [value1, value2, ...];

Example:
let names = [];
console.log(names); Output
let courses = ["HTML", "CSS", []
"Javascript", "React"]; [ 'HTML', 'CSS', 'Javascript', 'React' ]
console.log(courses);

2. Creating an Array using Array Constructor (JavaScript new Keyword)


The “Array Constructor” refers to a method of creating arrays by invoking the Array
constructor function. This approach allows for dynamic initialization and can be used to
create arrays with a specified length or elements.

Syntax:
let arrayName = new Array();

Example:
// Declaration of an empty array arr[1] = 20;
// using Array constructor arr[2] = 30;
let names = new Array(); console.log(arr);
console.log(names);
let courses = new Array("HTML", "CSS", Output
"Javascript", "React"); []
console.log(courses); [ 'HTML', 'CSS', 'Javascript', 'React' ]
let arr = new Array(3); [ 10, 20, 30 ]
arr[0] = 10;

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 console.log(courses[0]);


Values console.log(courses[1]);
let courses = ["HTML", "CSS", console.log(courses[2]);
"Javascript", "React"]; console.log(courses[3]);
NANDINI S D, GFGCW, H N PURA Page 37
WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

CSS
Output Javascript
HTML React

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 console.log("First Item: ", firstItem);


Values
let courses = ["HTML", "CSS", Output
"JavaScript", "React"]; First Item: HTML
let firstItem = courses[0];

3. Accessing the Last Element of an Array


We can access the last array element using [array.length – 1] index number.

// Creating an Array and Initializing with let lastItem = courses[courses.length - 1];


Values console.log("First Item: ", lastItem);
let courses = ["HTML", "CSS",
"JavaScript", "React"]; Output
First Item: React

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 console.log(courses);
Values
let courses = ["HTML", "CSS", Output
"Javascript", "React"]; [ 'HTML', 'CSS', 'Javascript', 'React' ]
console.log(courses); [ 'HTML', 'Bootstrap', 'Javascript', 'React' ]
courses[1]= "Bootstrap";

5. Adding Elements to the Array


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

// Creating an Array and Initializing with console.log(courses);


Values
let courses = ["HTML", "CSS", Output
"Javascript", "React"]; [ 'Web Development', 'HTML', 'CSS',
courses.push("Node.js"); 'Javascript', 'React', 'Node.js' ]
courses.unshift("Web Development");

NANDINI S D, GFGCW, H N PURA Page 38


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

6. Removing Elements from an Array


Remove elements using methods like pop(), shift(), or splice().

// Creating an Array and Initializing with Values


let courses = ["HTML", "CSS", "Javascript", "React", "Node.js"];
console.log("Original Array: " + courses);
// Removes and returns the last element
let lastElement = courses.pop();
console.log("After Removed the last elements: " + courses);
// Removes and returns the first element
let firstElement = courses.shift();
console.log("After Removed the First elements: " + courses);
// Removes 2 elements starting from index 1
courses.splice(1, 2);
console.log("After Removed 2 elements starting from index 1: " + courses);

Output
Original Array: HTML,CSS,Javascript,React,Node.js
After Removed the last elements: HTML,CSS,Javascript,React
After Removed the First elements: CSS,Javascript,React
After Removed 2 elements starting from index 1: CSS

7. Array Length
Get the length of an array using the length property.

// Creating an Array and Initializing with Values


let courses = ["HTML", "CSS", "Javascript", "React", "Node.js"];
let len = courses.length;
console.log("Array Length: " + len);

Output
Array Length: 5

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 courses = ["HTML", "CSS", "Javascript", "React", "Node.js"];
// Increase the array length to 7
courses.length = 7;
console.log("Array After Increase the Length: ", courses);
// Decrease the array length to 2
courses.length = 2;
NANDINI S D, GFGCW, H N PURA Page 39
WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

console.log("Array After Decrease the Length: ", courses)

Output
Array After Increase the Length: [ 'HTML', 'CSS', 'Javascript', 'React', 'Node.js', <2 empty
items> ]
Array After Decrease the Length: [ 'HTML', 'CSS' ]

9. Iterating Through Array Elements


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

Example: It is the example of for loop.


// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "JavaScript", "React"];
// Iterating through for loop
for (let i = 0; i < courses.length; i++) {
console.log(courses[i])
}

Output
HTML
CSS
JavaScript
React

10. Array Concatenation


Combine two or more arrays using the concat() method. Ir returns new array conaining
joined arrays elements.
// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "JavaScript", "React"];
let otherCourses = ["Node.js", "Expess.js"];
// Concatenate both arrays
let concateArray = courses.concat(otherCourses);
console.log("Concatenated Array: ", concateArray);

Output
Concatenated Array: [ 'HTML', 'CSS', 'JavaScript', 'React', 'Node.js', 'Expess.js' ]
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 courses = ["HTML", "CSS", "JavaScript", "React"];
// Convert array ot String
console.log(courses.toString());

NANDINI S D, GFGCW, H N PURA Page 40


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

Output
HTML,CSS,JavaScript,React

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 courses = ["HTML", "CSS", "JavaScript", "React"];
// Check type of array
console.log(typeof courses);

Output
Object

Objects in Javascript
Objects, in JavaScript, are the most important data type and form the building blocks for
modern JavaScript. These objects are quite different from JavaScript’s primitive data types
(Number, String, Boolean, null, undefined, and symbol) in the sense that these primitive
data types all store a single value each (depending on their types).

Syntax:
new Object(value)
Object(value)
let object_name = {
key_name : value,
...
}

Note:- Object() can be called with or without new. Both create a new object.

Example: Below is an example of Objects in JavaScript.


const o = new Object();
o.foo = 42;
console.log(o);
Output
{ foo: 42 }

JavaScript Object Properties


The property names can be strings or numbers. In case the property names are numbers,
they must be accessed using the “bracket notation” like this.

Example: Below is the example of object properties.

NANDINI S D, GFGCW, H N PURA Page 41


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

let school = {
name: 'Vivekananda School',
location: 'Delhi',
established: '1971',
20: 1000,
displayInfo: function () {
console.log(`The value of the key 20 is ${school['20']}`);
}
}
school.displayInfo();

Output
The value of the key 20 is 1000
But more on the bracket notation later. Property names can also be strings with more than
one space separated words. In which case, these property names must be enclosed in quotes
:
let school = {
"school name" : "Vivekananda School",
}

Inherited Properties
Inherited properties of an object are those properties that have been inherited from the
object’s prototype, as opposed to being defined for the object itself, which is known as the
object’s Own property. To verify if a property is an object’s Own property, we can use
the hasOwnProperty method. Property Attributes Data properties in JavaScript have
four attributes.
 value: The property’s value.
 writable: When true, the property’s value can be changed
 enumerable: When true, the property can be iterated over by “for-in” enumeration.
Otherwise, the property is said to be non-enumerable.
 configurable: If false, attempts to delete the property, change the property to be an
access-or property, or change its attributes (other than [[Value]], or changing
[[Writable]] to false) will fail.

Example: Below is the example of inherited properties.


// hasOwnProperty code in js
const object1 = new Object();
object1.property1 = 42;
console.log(object1.hasOwnProperty('property1'));

Output
True

Accessing Object Members


NANDINI S D, GFGCW, H N PURA Page 42
WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

Object members(properties or methods) can be accessed using the dot notation


(objectName.memberName);

Example: Below is the example of accessing object members.


let school = {
name : "Vivekanada",
location : "Delhi",
established : 1971,
20 : 1000,
displayinfo : function() {
console.log(`${school.name} was established
in ${school.established} at ${school.location}`);
}
}
console.log(school.name);
console.log(school.established);

Output
Vivekanada
1971

Bracket Notation
Syntax:
objectName["memberName"]

Example: Below is the example of Bracket Notation.


let school = {
name: "Vivekanada School",
location: "Delhi",
established: 1995,
20: 1000,
displayinfo: function () {
document.write(`${school.name} was established
in ${school.established} at ${school.location}`);
}
}
console.log(school['20']);

Output
Vivekanada School
1000

Unlike dot notation, the bracket keyword works with any string combination, including, but
not limited to multi-word strings.
NANDINI S D, GFGCW, H N PURA Page 43
WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

somePerson.first name // invalid


somePerson["first name"] // valid
Unlike dot notation, bracket notation can also contain names that are the results of any
expressions variables whose values are computed at run-time.
let key = "first name" somePerson[key] = "Name Surname"
Similar operations are not possible while using the dot notation.

Iterating over all keys of an object


To iterate over all existing enumerable keys of an object, we may use
the for…in construct. It is worth noting that this allows us to access only those properties
of an object which are enumerable (Recall that enumerable is one of the four attributes of
data properties). For instance, properties inherited from the Object.prototype are not
enumerable. But, enumerable properties inherited from somewhere can also be accessed
using the for…in construct

Example: Below is the example.


let person = {
gender: "male"
}
let person1 = Object.create(person);
person1.name = "Adam";
person1.age = 45;
person1.nationality = "Australian";
for (let key in person1) {
console.log(key);
}

Output
name
age
nationality
gender

Deleting Properties
To Delete a property of an object we can make use of the delete operator. An example of
its usage has been listed below.

Example: Below is the example of deleting properties.


let obj1 = {
propfirst : "Name"
}
console.log(obj1.propfirst);
delete obj1.propfirst
console.log(obj1.propfirst);
NANDINI S D, GFGCW, H N PURA Page 44
WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

Output
Name
Undefined

Window Object in JavaScript


In JavaScript, the Window object represents the window that contains a DOM
document.The Window object provides access to various properties and methods that
enable interaction with the browser environment, including manipulating the document,
handling events, managing timers, displaying dialog boxes, and more.

Window Object Properties


The Window object in JavaScript has numerous properties that provide access to various
aspects of the browser environment and the window itself. Some commonly used properties
include:
Property Name Description

The HTML document that is shown in the window is


window.document represented by the Document object, which is referred to by
the document property.

window.console The console gives the window’s Console Object back.

The location attribute makes reference to the Location


window.location
object, which has data about the page’s current URL.

window.defaultStatus It is now Abandoned.

window.closed If a window is closed, it returns a true boolean value.

window.frameElement It gives the window’s current frame back.

window.frame returns every window item currently active in the window.

window.history Retrieves the window’s History object.

It gives the number of iframe> elements currently present in


window.length
the window.

provides the ability to store key/value pairs in a web


window.localStorage
browser. stores data without a time.

NANDINI S D, GFGCW, H N PURA Page 45


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

Without including the toolbars and scrollbars, these


window.innerWidth and
characteristics describe the width & height of the browser
window.innerHeight
window.

It returns a pointer to the window that created the window in


window.opener
the opener function.

You can use outerHeight to return the height of the browser


window.outerHeight
window, including toolbars and scrollbars.

You can outerWidth to get the width of the browser


window.outerWidth
window, including toolbars and scrollbars.

window.name Returns or sets a window’s name.

window.parent Brings up the current window’s parent window.

Provides the ability to store key/value pairs in a web


window.sessionStorage
browser. Contains data for a single session.

window.scrollX It is a pageXOffset alias.

window.scrollY It is a pageYOffset alias.

window.self It provides the window’s current state.

window.status It is now Deprecated. Don’t employ it.

window.top It provides the top-most browser window back.

The screen attribute makes reference to the Screen object,


window.screen
which stands in for the screen that the browser is shown on.

The History object, which includes details about the current


window.history page’s browsing history, is the subject of the history
property.

The number of pixels that the current document has been


window.pageXOffset
scrolled horizontally.

window.pageYOffset The number of pixels that the current document has been

NANDINI S D, GFGCW, H N PURA Page 46


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

scrolled vertically.

The x-coordinate of the current window relative to the


window.screenLeft:
screen.

The y-coordinate of the current window relative to the


window.screenTop
screen.

The x-coordinate of the current window relative to the


window.screenX
screen (deprecated).

The y-coordinate of the current window relative to the


window.screenY
screen (deprecated).

window.navigator An object representing the browser and its capabilities

Frame objects:
The HTML DOM Window frames property in HTML DOM is used to return the frame
element in the form of an array object. This property represents all <iframe> elements in
the current window. DOM Windowframe is a read-only property.

Syntax:
window.frames

Properties:
 length property: It returns the number of iframe elements in the current window.
 location property: It changes the location of the iframe.

Return Value: It returns a reference to the Window object, representing all the frames in
the current window.
JavaScript Events
Javascript has events to provide a dynamic interface to a webpage. These events are
hooked to elements in the Document Object Model(DOM).
These events by default use bubbling propagation i.e, upwards in the DOM from children
to parent. We can bind events either as inline or in an external script.

Syntax:
<HTML-element Event-Type = "Action to be performed">

These are some javascript events:


JavaScript onclick events: This is a mouse event and provokes any logic defined if the
user clicks on the element it is bound to.
NANDINI S D, GFGCW, H N PURA Page 47
WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

JavaScript onkeyup event: This event is a keyboard event and executes instructions
whenever a key is released after pressing.

onmouseover event: This event corresponds to hovering the mouse pointer over the
element and its children, to which it is bound to.

JavaScript onmouseout event: Whenever the mouse cursor leaves the element which
handles a mouseout event, a function associated with it is executed.

JavaScript onchange event: This event detects the change in value of any element listing
to this event.

JavaScript onload event: When an element is loaded completely, this event is evoked.

JavaScript onfocus event: An element listing to this event executes instructions whenever
it receives focus.

JavaScript onblur event: This event is evoked when an element loses focus.

JavaScript Date prototype Property


The date.prototype property represents the prototype for the Date constructor. The
prototype allows adding new properties, and methods.

Javascript exception handling:


When executing JavaScript code, errors will definitely occur. These errors can occur due to
a fault from the programmer’s side or the input is wrong or even if there is a problem with
the logic of the program.
But all errors can be solved and to do so we use five statements that will now be explained.
 The try statement lets you test a block of code to check for errors.
 The catch statement lets you handle the error if any are present.
 The throw statement lets you make your own errors.
 The finally statement lets you execute code after try and catch.
The finally block runs regardless of the result of the try-catch block.
Below are examples, that illustrate the JavaScript Errors Throw and Try to Catch:

Example:
try {
dadalert("Welcome Fellow Geek!");
}
catch (err) {
console.log(err);
}

NANDINI S D, GFGCW, H N PURA Page 48


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

Output: In the above code, we make use of ‘dadalert’ which is not a reserved keyword and
is neither defined hence we get the error.

Try and Catch Block


The try statement allows you to check whether a specific block of code contains an error or
not. The catch statement allows you to display the error if any are found in the try block.
try {
Try Block to check for errors.
}
catch(err) {
Catch Block to display errors.
}

Example: In this example, we will see the usage of try-catch block in javascript.
try {
dadalert("Welcome Fellow Geek!");
}
catch (err) {
console.log(err);
}

Output:

Javascript Throws Block The throw Statement


When any error occurs, JavaScript will stop and generate an error message. The throw
statement lets you create your own custom error. Technically you can throw your custom
exception (throw an error). The exception can be a JavaScript Number, String, Boolean, or
Object. By using throw together with try and catch, you can easily control the program
flow and generate custom error messages.

Example: In this example, we will see how a throw statement is used to throw an error in
javascript.
try {
throw new Error('Yeah... Sorry');
}
catch (e) {
console.log(e);
}

NANDINI S D, GFGCW, H N PURA Page 49


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

Output:

The finally Block


The finally Statement runs unconditionally after the execution of the try/catch block. Its
syntax is
try {
Try Block to check for errors.
}
catch(err) {
Catch Block to display errors.
}
finally {
Finally Block executes regardless of the try / catch result.
}

Example: In this example, we will learn about the final statement of Javascript.
try {
console.log('try');
} catch (e) {
console.log('catch');
} finally {
console.log('finally');
}

Output: The Finally Block can also override the message of the catch block so be careful
while using it.

HTML DOM Form Object


The Form Object in HTML DOM is used to represent the HTML < form > element. This
tag is used to set or get the properties of < form > element. This element can be accessed
by using getElementById() method.

NANDINI S D, GFGCW, H N PURA Page 50


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

Syntax:
document.getElementById("Form_ID");

Note: This Form_ID is assigned to HTML < form > element.

Example: Returning “form id” using document.getElementById(“myForm”).id;.


<h1 style="color:green;"> <script>
GFG function my() {
</h1> // Accessing form element.
<h2>DOM Form Object</h2> var txt = document.getElementById(
<form id="myForm" method="GET" "myForm").id;
target="_blank" document.getElementById(
action="/action_page.php"> "G_p").innerHTML = txt;
First name: }
<br> </script>
<input type="text" name="fname"
placeholder="FName"> Output
<br>
<br> Last name:
<br>
<input type="text" name="lname"
placeholder="LName">
<br>
<br>
</form>
<button onclick="my()">
Submit
</button>
<p id="G_p" style="color:green;
font-size:30px;">
</p>

JSON
JSON stands for JavaScript Object Notation. It is a format for structuring data. This format is
used by different web applications to communicate with each other. It is the replacement of the
XML data exchange format. It is easy to struct the data compare to XML. It supports data
structures like arrays and objects and the JSON documents that are rapidly executed on the
server.

Why JSON?
It is a Language-Independent format that is derived from JavaScript. It is Human-readable and
writable. It is a lightweight text-based data interchange format which means, it is simpler to
read and write when compared to XML. Though it is derived from a subset of JavaScript, yet

NANDINI S D, GFGCW, H N PURA Page 51


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

it is Language independent. Thus, the code for generating and parsing JSON data can be
written in any other programming language.

Syntax Rules: Data is in name/value pairs and they are separated by commas. It uses curly
brackets to hold the objects and square brackets to hold the arrays.

Example:
{
"Data Structures": [
{
"Name" : "Trees",
"Course" : "Intoduction of Trees",
"Content" : [ "Binary Tree", "BST",
"Generic Tree"]
},
{
"Name" : "Graphs",
"Topics" : [ "BFS", "DFS", "Topological Sort" ]
}
]
}

JavaScript BOM Window Screen


The Browser Object Model (BOM) is a browser-specific convention referring to all the
objects exposed by the web browser. The BOM allows JavaScript to “interact with” the
browser. The object of the window represents a browser window and all its corresponding
features. A window object is created automatically by the browser itself. Java Script’s
window.screen object contains information about the user’s screen. It can also be written
without the window prefix.

Properties:
 screen.width
 screen.height
 screen.availWidth
 screen.availHeight
 screen.colorDepth
 screen.pixelDepth

HTML screen.width Property: The screen.width property returns the user’s screen width
in pixels.

HTML screen.height Property: The screen.height property returns the users screen height
in pixels.

NANDINI S D, GFGCW, H N PURA Page 52


WEB TECHNOLOGIES (6TH SEM BSc)(NEP)

HTML screen.availWidth Property: The screen.availWidth property returns the users


screen width in pixels, excluding the interface features.

HTML screen.availHeight Property: The screen.availHeight property returns the users


screen height in pixels excluding the interface features.

HTML screen.colorDepth Property: The screen.colorDepth property returns the bits


(number) to be used to display one color. Usually, 24-bit or 32-bit hardware is used for
color resolution. 24 bits = 16, 777, 216 different (True Colors) 32 bits = 4, 294, 967, 296
different (Deep Colors)

HTML screen.pixelDepth Property: The screen.pixelDepth property returns the pixel


depth of the screen.

NANDINI S D, GFGCW, H N PURA Page 53

You might also like