0% found this document useful (0 votes)
6 views129 pages

WT 3 Unit

Client-side scripting allows web pages to run scripts directly in the user's browser without server interaction, enhancing user interfaces with dynamic features like menus and animations. JavaScript, along with jQuery and VBScript, are the most popular client-side scripting languages, enabling functionalities such as data validation and interactive web elements. While client-side scripting offers advantages like reduced server load and ease of learning, it also presents security risks and dependency on the user's browser settings.

Uploaded by

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

WT 3 Unit

Client-side scripting allows web pages to run scripts directly in the user's browser without server interaction, enhancing user interfaces with dynamic features like menus and animations. JavaScript, along with jQuery and VBScript, are the most popular client-side scripting languages, enabling functionalities such as data validation and interactive web elements. While client-side scripting offers advantages like reduced server load and ease of learning, it also presents security risks and dependency on the user's browser settings.

Uploaded by

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

UNIT -3

What is Client Side Script?

Client-side scripting is when the server sends the code along with the HTML web page to the
client. The script is referred to by the code.

In other words, client-side scripting is a method for browsers to run scripts without having to
connect to a server.

The code runs on the client’s computer’s browser either while the web page is loading or after it
has finished loading.

Client-side scripting is mostly used for dynamic user interface components including pull-
down menus, navigation tools, animation buttons, and data validation.

It is currently quickly expanding and evolving on a daily basis. As a result, creating client-side
web programming has become easier and faster, lowering server demand.

By far the most popular client-side scripting languages or web scripting languages, JavaScript and
jQuery are frequently utilized to construct dynamic and responsive webpages and websites.

The browser downloads the code to the local machine (temporarily) and begins
processing it without the server. As a result, client-side scripting is browser-specific.

A client-side script is a small program (or set of instructions) that is embedded


(or inserted) into a web page. It is processed within the client browser instead of
the web server.
The client side script downloads at the client end from the server along with the
HTML web page it is embedded in. The web browser interprets and executes the
code and then displays the results on the monitor.
The script that executes on the user’s computer system is called client. It is
embedded (or inserted) within the HTML document or can be stored in an
external separate file (known as external script).
The script files are sent to the client machine from the web server (or servers)
when they are requested. The client’s web browser executes the script, then
displays the web page, including any visible output from the script.
Look at the below figure to understand better.

Client side scripts may also have some instructions for the web browser to follow
in response to certain user actions, such as pressing a page button. They can
often be looked if client want to view the source code of web page.
Popular Client Side Scripting Language

A language in which a client side script or program is written using syntax is called
client side scripting language or client side programming.
The most popular client side scripting languages is as follows:
1. JavaScript: It is the most widely client side scripting or programming
language. It is based on ECMAScript standard language.
JavaScript is an object based oriented, dynamically typed (or also called weakly
typed) scripting language. It runs directly on the browser with the help of an inbuilt
interpreter.

Here, weakly typed means the variables are easily converted implicitly from one
data type to another.
2. VBScript: This scripting language is developed by Microsoft, based on the
Visual Basic. It is basically used to enhance the features of web pages in Internet
Explorer. VBScript is interpreted by Internet Explorer web browser.
3. jQuery: jQuery is a fast, small, lightweight JavaScript library. It is used to
facilitate a lot of JavaScript code into simple-to-use-functionality.
Most of the biggest companies such as Google, Microsoft, IBM, Netflix, etc. on
the Web are using jQuery language.
Client Side Scripting Language Example

Let’s take a very simple example of JavaScript client side script. In this example, a
simple JavaScript client side script will run in the browser to display the name of
cities.
The HTML file located on the server will be the same one sent to the browser, but
JavaScript changes the HTML web page that is loaded in the browser.
Example

Look at the below diagram that shows the flow of data between server and browser.
Application of Client Side Scripting

Client side scripting is used to make web pages or website more interactive. It is
primarily used at the frontend, where the user can see using the browser.
Some important applications of client side scripting are listed, as below:
● To retrieve data from web browser or user’s screen.
● Used in the field of online games.
● To customize the web page without reloading the page.
● Client side scripting is used for validation purpose. If the user enters
incorrect credentials on the login page, the web page displays an error
message on the client machine without submitting it to the web server.
● To create ad banners that interact with the user, rather than simply
displaying graphics.
● To create animated images that change when we move the mouse over
them.
● Client side script can be used to detect installed plug-ins and notify the user
if a plugin is required.
Advantages of Client Side Scripting

There are several great advantages of client side scripting that are as follows:
1. The client side scripting language is quite easy to learn and use. It requires
minimum programming knowledge or experienced required.
2. The main advantage of client side scripting is that it is lightweight and
relatively easy to implement (syntax not too complex). The editing and
executing the code is fast.
3. Data processing is done on the client side from the server, which makes it
easier to scale applications with large numbers of users. Thereby, load on the
server reduces.
4. The client side data validation can be possible using the client side
scripting language like JavaScript.
6. Mathematical assessment is also possible using client side scripting.
7. Script code only executed by the browser without connecting the server.
Disadvantages of Client Side Scripting

There are certain disadvantages of client side scripting that are as follows:
1. The main disadvantage of client side scripting is that it is unsecure because the
code is sent as is to the client and, therefore, visible to it if the client looks at the
sources of his web page. In short, code is usually visible.
2. Client side programming cannot be used if we need to access databases or
needs to transmit sensitive data over the internet.
3. There is no guarantee that user has enabled JavaScript on his computer’s
browser. Therefore, any required functionality must be loaded on the server
despite the possibility that it could be offloaded.
4. The smooth running of the script (or program) depends entirely on the
client’s browser, its configuration, and security level.
5. The web application based on the heavy JavaScript can be complicated to
debug and maintain.
6. Client side scripting languages are usually more limited in functionality than
server side scripting language
What is JavaScript (JS)?
JavaScript (js) is a light-weight object-oriented programming language which is
used by several websites for scripting the webpages. It is an interpreted, full-
fledged programming language that enables dynamic interactivity on websites
when applied to an HTML document. It was introduced in the year 1995 for adding
programs to the webpages in the Netscape Navigator browser. Since then, it has
been adopted by all other graphical web browsers. With JavaScript, users can
build modern web applications to interact directly without reloading the page
every time. The traditional website uses js to provide several forms of interactivity
and simplicity.

Although, JavaScript has no connectivity with Java programming language. The


name was suggested and provided in the times when Java was gaining popularity
in the market. In addition to web browsers, databases such as 1=890[pouchDB
and MongoDB uses JavaScript as their scripting and query language.

JavaScript is the full form of JS. It is a programming language that is utilized to


build an interactive website as it adds functionality to the web pages. It first
appeared on December 4, 1995. Initially, it was created by Brendan Eich of
Netscape. Web browsers consist of a separate JavaScript engine which is utilized
to execute the JS code. One of the most famous JavaScript runtime environments
is Node.js. It is a high-level, lightweight, cross-platform, single-threaded and
just-in-time compile language that follows ECMAScript standard.

JS is the most popular programming in the world right now. It is growing faster
than any other language. Big companies like PayPal, Netflix and more build
internal applications around JS.

JavaScript is a programming language used to create dynamic content for


websites. It is a lightweight, cross-platform, and single-threaded
programming language. JavaScript is an interpreted language that executes code line
by line providing more flexibility.

● HTML adds Structure to a web page, CSS styles it and JavaScript

brings it to life by allowing users to interact with elements on the

page, such as actions on clicking buttons, filling out forms, and

showing animations.

● JavaScript on the client side is directly executed in the user's browser.

Almost all browsers have JavaScript Interpreter and do not need to

install any software. There is also a browser console where you can

test your JavaScript code.

● JavaScript is also used on the Server side (on Web Servers) to

access databases, file handling and security features to send

responses, to browser
Introduction to JavaScript

JavaScript is a scripting language that is used to create and manage dynamic web
pages, basically anything that moves on your screen without requiring you to
refresh your browser. It can be anything from animated graphics to an
automatically generated Facebook timeline.

When most people get interested in web development, they start with good old
HTML and CSS. From there, they move on to JavaScript, which makes sense,
because, these three elements together form the backbone of web development.

● HTML is the structure of your page like the headers, the body
text, any images you want to include. It basically defines the
contents of a web page.
● CSS controls how that page looks (it’s what you’ll use to
customize fonts, background colors, etc.).

● JavaScript is the third element. Once you’ve created your


structure (HTML) and your aesthetic vibe (CSS), JavaScript
makes your site dynamic (automatically updateable).
Why JavaScript?

JavaScript is an essential programming language, almost compulsory to learn for


students or software developers that are gravitated towards web development.
Wondering why? Here’s the answer:

● Javascript is the most popular programming language in the world and


that makes it a default choice for web development. There are many
frameworks available which you can use to create web applications once
you have learned JavaScript.
● JavaScript offers lots of flexibility. You can create stunning and fast
web applications with tons of customizations to provide users with
the most relevant graphical user interface.
● JavaScript is now also used in mobile app development, desktop app
development, and game development. This opens many possibilities for
you as a Javascript developer.
● Due to the high demand in the industry, there are tons of job
growth opportunities and high pay for those who know
JavaScript.
● The incredible thing about Javascript is that you can find tons of
frameworks and libraries already developed, which can be used directly
in web development. That reduces the development time and enhances
the graphical user interface.
What is JavaScript Used For?

JavaScript is used in various fields from the web to servers, and here’s a quick list
of the significant areas it’s used in:

Fig: JavaScript applications

● Web Applications: JavaScript is used for adding interactivity and


automation to websites. So, if you want your web application to be
anything more than just a static page of contents, you’ll probably need to
do some “JavaScript’ing.”
● Mobile Applications: JavaScript isn’t just for developing web applications;
it is also used for developing applications for phones and tablets. With
frameworks like React Native, you can develop full-fledged mobile
applications with all those fancy animations.
● Web-based Games: If you’ve ever played a game directly on the web
browser, JavaScript was probably used to make that happen.
● Back-end Web Development: JavaScript has traditionally been used
for developing the front-end parts of a web application. However,
with the introduction of NodeJS, a prevalent back-end JavaScript
framework, things have changed. And now, JavaScript is used for
developing the back-end structure also.
Say “Hello World” in JavaScript

The next step is to write code. Here’s how you can write a simple JavaScript code
that prints Hello World on the browser window.
<html>
<body>
<script language="javascript" type="text/javascript">
document.write("Hello World!");
</script>
</body>
</html>

● JavaScript can be easily integrated into the HTML code, and that’s
exactly what’s happening here.
● For those of you not familiar with HTML, this code might seem a bit
unfamiliar. But it is perfectly understandable even to web development
beginners.
● <html> tag is required to define a HTML web page. <head> tag. The web
page contents are defined inside the <body> tag.
● Any JavaScript that you add to the web page has to be within the <script> tag.
● document.write is a JavaScript function that writes the contents onto the
web page. In this case, it prints “Hello World!” on screen.

While HTML and CSS are absolutely required to code a basic web page, JavaScript
is the language that will help you bring that page to life, making it more attractive
to the audience. Taking the time to learn JavaScript will help you in the web
development world.
JavaScript Code
<html>
<head></head>
<body>
<h1>Check the console for the message!</h1>
<script>
// This is our first JavaScript program
console.log("Hello, World!");
</script>
</body>
</html>

In this example

● The<script> tag is used to include JavaScript code inside an HTML


document.
● console.log() prints messages to the browser’s developer console.
Open the browser console to see the “Hello, World!” message.

Features of JavaScript:
There are many features of JavaScript which are as follows:
Light eight

It is a lightweight programming language that is made for handling data on the


client side.

Dynamic typing

It is a dynamic typing programming language which means variable types are


specified on the basis of the stored value. Some data types are cast implicitly on
the basis of the operation utilized.

Object-oriented programming

It supports object-oriented programming. There are two essential principles in


JavaScript which are encapsulation and inheritance.

Functional Style

It utilizes a functional style as the objects can be created by utilizing a constructor.


In JavaScript, functions are utilized as objects and passed to the other functions
also.
Platform Independent

It is a platform independent language which means it is portable and can be run


on any operating system. You have to write it once and run it anywhere.

Prototype-based

It is a prototype-based language which means it utilizes prototypes in place of


classes. We can specify an object prototype and after that, we can construct more
objects with the help of the specified object prototype.

Interpreted Language

It is an interpreted programming language which means it executes the code line


by line. A JavaScript interpreter is a built-in feature which is provided by each
browser and utilized to interpret the code. At present, an interpreter called
just-in-time is utilized by many browsers.
Single-threaded

It supports single threading which means it can only do a single task at a time but
JavaScript can implement parallel execution with the help of async processing and
web workers.

Async Processing: If there are many functions that need to be executed then
utilizing async processing allows us to process functions in parallel that means
functions are not executed one by one but can be executed in parallel.

Web Worker: When there is heavy-duty work then web worker is utilized to run
tasks in background threads by processing a parallel execution.

Zero-based numbering

It is a zero-index programming language which means the initial element of a


sequence is given the index 0 instead of index 1.

Applications of JavaScript
There are multiple applications of JavaScript, some of them are as follows:
Web Development:

The main application of JavaScript is web development. JavaScript is utilized to


create web pages. It brings web pages to life by creating a dynamic and
interactive web pages. Many big companies use this language to build a web page
which gives better user experience. There are various websites that are
constructed with the help of JavaScript such as Google, Facebook, Yahoo, Twitter,
Amazon, Wikipedia, LinkedIn, YouTube, Quora, and more.

Server applications:

Server-side applications can be created by utilizing JavaScript. A JS runtime


environment called Node.js is utilized to construct server-side applications. Some
of the big companies such as PayPal, GoDaddy, etc., are utilizing Node.js for
server apps.

Web Applications:

Web applications are constructed with the help of JavaScript. The frameworks of
JavaScript such as Angular, React, etc., are utilized to build robust web apps.

Game development:

JavaScript is a great language for creating games on the web. Both HTML5 and
JavaScript are used together to develop games. The library called EaselJS provides
rich graphics so it is utilized for graphics. Some of the games created using HTML5
and JS are Rock Paper Scissor, Snake Game, Tic Tac Toe, etc.

Presentations:

JavaScript is used to make interactive presentations by utilizing libraries like


BespokeJS and RevealJS. The BespokeJS framework is used to add animated
bullets, syntax highlighting, and more. The RevealJS framework is used to create
stylish presentations consisting of themes, slide backgrounds, etc.
Mobile App Development:

Mobile applications are very popular these days as they are convenient to use.
There are various frameworks of JavaScript such as React Native, Apache
Cordova, Mobile Angular UI, jQuery Mobile, and more, are used to create mobile
applications. Some of the mobile apps created using JS frameworks are Netflix,
Candy Crush, Uber, Facebook, etc.

Dra ing Applications:

HTML in JavaScript provides a feature called the canvas element which is used to
make drawings on web pages. This feature has opened a gateway for creating
digital art projects. The canvas element allows us to draw freely, provides many
colors, and much more.

Smart atches Applications

Smartwatches are getting popular these days as they act as a substitute for
mobiles. JS libraries like Pebble are utilized for creating apps for smartwatches.

Charts and Reports

JavaScript consists of a library called Chart.js which is utilized to create charts and
reports. The Chart.js provides various features such as device pixel ratio, data
decimation, responsive charts, etc.

Key Features of JavaScript


● Client-Side Scripting:JavaScript runs on the user’s browser, so has a

faster response time without needing to communicate with the server.

● Versatile: JavaScript can be used for a wide range of tasks, from

simple calculations to complex server-side applications.

● Event-Driven: JavaScript can respond to user actions (clicks,

keystrokes) in real-time.
● Asynchronous: JavaScript can handle tasks like fetching data from

servers without freezing the user interface.

● Rich Ecosystem: There are numerous libraries and frameworks built on

JavaScript, such as React, Angular, and Vue.js, which make

development faster and more efficient.

Client Side and Server Side nature of JavaScript


● Client-side: Involves controlling the browser and its DOM, handling

user events like clicks and form inputs. Libraries such as AngularJS,

ReactJS, and VueJS are commonly used.

● Server-side: Involves interacting with databases, manipulating files, and

generating responses. With Node.js and frameworks like Express.js,

JavaScript is also widely used on the server side.

Imperative Programming: Focuses on how to perform tasks, controlling

the flow of computation. It includes approaches like procedural and

object-oriented programming, often using constructs like async/await to

handle actions.

● Declarative Programming: Focuses on what should be done rather than

how it’s done. It emphasizes describing the desired result, like with

arrow functions, without detailing the steps to achieve it.


Applications of JavaScript
● Web Development: JavaScript adds interactivity and dynamic behavior

to static websites, with popular frameworks like AngularJS enhancing

development.

● Web Applications: JavaScript powers robust web applications,

leveraging APIs, React, and Electron to create dynamic user

experiences like Google Maps.

● Server Applications: Node.js brings JavaScript to the server side,

enabling powerful server applications and full-stack development.

● Game Development: JavaScript, combined with HTML5 and libraries

like Ease JS, enables the creation of interactive games for the web.

● Smartwatches: Pebble JS allows JavaScript to run on smartwatches,

supporting apps that require internet connectivity.

Limitations of JavaScript
● Security Risks : JavaScript can be used for attacks like Cross-Site

Scripting (XSS), where malicious scripts are injected into a website to

steal data by exploiting elements like <img>, <object>, or

<script> tags.

● Performance : JavaScript is slower than traditional languages for

complex tasks, but for simple tasks in a browser, performance is

usually not a major issue.


● Complexity : To write advanced JavaScript, programmers need to

understand core programming concepts, objects, and both client-

and server-side scripting, which can be challenging.

● Weak Error Handling and Type Checking : JavaScript is weakly typed,

meaning variables don’t require explicit types. This can lead to issues

as type checking is not strictly enforced.

● DataTypes


∙ Numbers - are values that can be processed and calculated. You don't
enclose them in quotation marks. The numbers can be either positive
or negative.
● ∙ Strings - are a series of letters and numbers enclosed in quotation
marks. JavaScript uses the string literally; it doesn't process it. You'll
use strings for text you want displayed or values you want passed
along.
● ∙ Boolean (true/false) - lets you evaluate whether a condition
meets or does not meet specified criteria.
● ∙ Null - is an empty value. null is not the same as 0 -- 0 is a real,
calculable number, whereas null is the absence of any value.

● Data Types
TYPE EXAMPLE
Numbe Any number, such as 17, 21, or 54e7
rs
Strings "Greetings!" or "Fun"
Boole Either true or false
an
Null A special keyword for exactly that – the null value
(that is, nothing)

JavaScript variables are used as container to store values, and they can be of any
data type. You can declare variables using the var, let, or const keywords.
JavaScript provides different ways to declare multiple variables either individually
or in a single line for efficiency and readability.
I variable is a name given to the memory location that helps us to store some
form of data and retrieves it when required. It allows us to refer to memory
location without having to memorize the memory address. A variable name can
be used in expressions as a substitute in place of the value it stores.

var a = 10 // Old style


let b = 20; // Prferred for non-const
const c = 30; // Preferred for const (cannot be changed)

console.log(a);

console.log(b);

console.log(c);

JavaScript Variables
The following are the rules for naming variables in JavaScript:

● Spaces are not allowed in variable names.

● Only letters, digits, underscores, and dollar signs are permitted in

variable names.

● Case matters when it comes to variable names.

● A letter (alphabet), an underscore (_), or a dollar sign (3) must be the

first character in a variable name, any other special characters must

not be taken.

● certain terms such as reserved words in javascript shouldn’t be used to

name variables.

JavaScript Var Statement

The var keyword was used in all JavaScript code from 1995 to 2015.

The let and const keywords were added to JavaScript in 2015.

The var keyword should only be used in code written for older browsers.

Without using any keywords.


Using the 'var' keyword.
Using the 'let' keyword. Using
the 'const' keyword.

The let and const keywords were introduced to JavaScript in 2015 (ES6). Prior to
ES6, only var keyword was used to declare the variable in JavaScript. In this
section, we will discuss 'var' keyword. We will cover the 'let' and 'const' keywords
in subsequent chapters.

Variable Declaration in JavaScript

You

JavaScript ‘let’ Definition

The let keyword in JavaScript is used to declare a block-scoped local variable, optionally
initializing it to a value. It’s part of the ECMAScript 2015 (ES6) specification. Variables declared
with let have their scope in the block for which they are defined, as well as in any contained sub-
blocks. This differs from

variables declared with var, which have their scope in the entire enclosing function.

Syntax of JavaScript ‘let’

The let keyword in JavaScript is used for declaring a variable with block scope,
potentially initializing it to a value. The syntax is as follows:

1. Declaration

let variableName;
2. Initialization

let variableName = value;

Where,

● variableName: Name of the variable.


● value: Initial value assigned to the variable.
Characteristics of ‘let’

● Block Scope: Unlike var, which is function-scoped, variables declared


with let are block-scoped. This means they only exist within the nearest
set of curly braces ({}) such as those used in loops, if-statements, or
other blocks.
● No Hoisting to Scope Start: Variables declared with let are hoisted but
not initialized. This means the variable exists during the entire block but
cannot be accessed until after the declaration is encountered. Accessing
the variable before the declaration results in a ReferenceError.
● No Re-Declaration in the Same Scope: With let, re-declaring the
same variable within the same scope is not allowed and results in a
syntax error. This helps avoid accidental re-declarations, which can
lead to bugs.
Temporal Dead Zone: The period from the start of the block until the declaration is
reached is known as the Temporal Dead Zone (TDZ) for that variable. During this time,
the variable is in a “dead zone” where accessing

Examples of JavaScript ‘let’

1. Basic Declaration and Initialization

let message = 'Welcome to Shiksha Online!';


console.log(message);

JavaScript ‘var’ Definition


The var keyword in JavaScript is used to declare a variable. It’s one of the ways to
store data values, and its usage has several characteristics that distinguish it from
other variable declaration keywords like let and const.

Syntax of JavaScript ‘var’

The var keyword in JavaScript is used for declaring a variable, potentially


initializing it to a value. The syntax is as follows:

1. Declaration

var variableName;
2. Initialization

var variableName = value;

Where,

● variableName: Name of the variable.


● value: Initial value assigned to the variable.

Characteristics of ‘var‘
● Function Scope: Variables declared with var are scoped to the
nearest function block. If declared outside of a function, they are
globally scoped.
● Hoisting: var declarations are “hoisted” to the top of their scope. This
means that the variable can be used before it’s declared, although it will
be undefined until its declaration and initialization (if any) are reached in
● Re-Declaration: Variables declared with var can be re-declared
within the same scope without causing an error, which can lead to
bugs if done accidentally.
● Initialization: If you declare a variable with var without initializing it (i.e.,
without assigning it a value), it will have the value undefined.

Examples of JavaScript ‘var’

1. Basic Usage

var greeting = "Hello from ShikshaOnline!";


console.log(greeting);

In JavaScript, const is a keyword used to declare constants. Once assigned, the


value of a constant cannot be changed. It provides a way to create read-only
variables. Attempting to reassign a const variable will result in a syntax error.

These are the following ways to use const:

Declaring a Constant Variable


The const keyword in JavaScript is primarily used for declaring constants. The
value of a const variable cannot be reassigned after initialization.
Example: This example shows the declaration of some constant by using the

Examples of JavaScript ‘let’

1. Basic Declaration and Initialization

let message = 'Welcome to Shiksha Online!';


console.log(message);
JavaScript ‘var’ Definition

The var keyword in JavaScript is used to declare a variable. It’s one of the ways to
store data values, and its usage has several characteristics that distinguish it from
other variable declaration keywords like let and const.

Syntax of JavaScript ‘var’

The var keyword in JavaScript is used for declaring a variable, potentially


initializing it to a value. The syntax is as follows:

3. Declaration

var variableName;
4. Initialization

var variableName = value;

Where,

● variableName: Name of the variable.


● value: Initial value assigned to the variable

Characteristics of ‘var‘

● Function Scope: Variables declared with var are scoped to the


nearest function block. If declared outside of a function, they are
globally scoped.
● Hoisting: var declarations are “hoisted” to the top of their scope. This
means that the variable can be used before it’s declared, although it will
be undefined until its declaration and initialization (if any) are reached in
the code.
● Re-Declaration: Variables declared with var can be re-declared
within the same scope without causing an error, which can lead to
bugs if done accidentally.
● Initialization: If you declare a variable with var without initializing it (i.e.,
without assigning it a value), it will have the value undefined.

● Function Scope: Variables declared with var are scoped to the


nearest function block. If declared outside of a function, they are
globally scoped.
● Hoisting: var declarations are “hoisted” to the top of their scope. This
means that the variable can be used before it’s declared, although it will
be undefined until its declaration and initialization (if any) are reached in
the code.
● Re-Declaration: Variables declared with var can be re-declared
within the same scope without causing an error, which can lead to
bugs if done accidentally.
● Initialization: If you declare a variable with var without initializing it (i.e.,
without assigning it a value), it will have the value undefined.
Examples of JavaScript ‘var’

2. Basic Usage

var greeting = "Hello from ShikshaOnline!";


console.log(greeting);

In JavaScript, const is a keyword used to declare constants. Once assigned, the


value of a constant cannot be changed. It provides a way to create read-only
variables. Attempting to reassign a const variable will result in a syntax error.

These are the following ways to use const:

Declaring a Constant Variable


The const keyword in JavaScript is primarily used for declaring constants. The
value of a const variable cannot be reassigned after initialization.

Example: This example shows the declaration of some constant by using the
const keyword.

const PI = 3.14159; console.log(PI); //


Output: 3.14159

// Attempting to reassign the value of a


// const variable will result in an error
// PI = 3.14; // Error: Assignment to constant variable.

What are JavaScript Operators?

JavaScript operators are special symbols used in scripts to perform


operations on operands, such as arithmetic calculations, logical
comparisons, or value assignments. It plays a crucial role in
controlling the flow and processing of data within the language.

Just like other programming languages, JavaScript offers various


operators to perform distinct functions. JavaScript operators can
be categorized into 5 types: Arithmetic, Assignment, Comparison,
Logical and Conditional. Let’s know about each of them with the
help of examples.

JavaScript operators are symbols that are used to execute


operations on operands. Operands are the variables they operate
on.

For example:

If we add 3 and 7, we

get 10 as a result.

3+7=10
In this case, 3 and 7 are operands, whereas + is an operator.

JavaScript Arithmetic

As with algebra, you can do arithmetic operations with JavaScript variables:


y=x-5;
z=y+5;
JavaScript Operators

The operator = is used to assign

values. The operator + is used to

add values.

The assignment operator = is used to assign values to JavaScript

variables. The arithmetic operator + is used to add values

together.

y=
z=
2;
x=y+z;

The value of x, after the execution of the statements above is 7.

JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic

between variables and/or values. Given that y=5, the table

below explains the arithmetic operators:

Operator Description Example Result


+ Addition x=y+2 x=7
- Subtraction x=y-2 x=3
* Multiplication x=y*2 x=10
/ Division x=y/2 x=2.5
% Modulus (division remainder) x=y%2 x=1
++ Increment x=++y x=6
-- Decrement x=--y x=4

JavaScript Assignment Operators

Assignment operators are used to assign values to JavaScript

variables. Given that x=10 and y=5, the table below explains the

assignment operators:

Operator Example Same As Result


= x=y x=5
+= x+=y x=x+y x=15
-= x-=y x=x-y x=5
*= x*=y x=x*y x=50
/= x/=y x=x/y x=2
%= x%=y x=x%y x=0

The + Operator Used on Strings

The + operator can also be used to add string variables or text

values together. To add two or more string variables together, use

the + operator.

txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
After the execution of the statements above, the variable txt3 contains

"What a verynice day". To add a space between the two strings, insert a

space into one of the strings:

txt1="What a very ";


txt2="nice day";
txt3=txt1+txt2;

or insert a space into the expression:


txt1="What a very";
txt2="nice day";
txt3=txt1+" "+txt2;

After the execution of the statements above, the variable txt3

contains: "What a very nice day"

Adding Strings and Numbers

Look at these examples:


x=5+5;
document.write(x);

x="5"+"5";
document.write(x);

x=5+"5";
document.write(x);

x="5"+5;
document.write(x);
The rule is:

If you add a number and a string, the result will be a

string. JavaScript Comparison and Logical Operators

Comparison and Logical operators are used to test for true or false.

Comparison Operators

Comparison operators are used in logical statements to determine equality or


difference between variables or values.

Given that x=5, the table below explains the comparison operators:
Operator Description Example
== is equal to x==8 is false
=== is exactly equal to (value and type) x===5 is true
x==="5" is false
!= is not equal x!=8 is true
> is greater than x>8 is false
< is less than x<8 is true
>= is greater than or equal to x>=8 is false
<= is less than or equal to x<=8 is true

How Can it be Used

Comparison operators can be used in conditional statements to compare values


and take action depending on the result:
if (age<18) document.write("Too young");

You will learn more about the use of conditional statements in the
next chapter of this tutorial. Logical Operators

Logical operators are used to determine the logic between

variables or values. Given that x=6 and y=3, the table below
Operator Description Example
explains
&& the logical operators: and (x < 10 && y > 1) is true

|| or (x==5 || y==5) is false

! not !(x==y) is true

Conditional Operator

JavaScript also contains a conditional operator that assigns a value to a variable


based on some condition.
Syntax
variablename=(condition)?value1:value2

Example
greeting=(visitor=="PRES")?"Dear President ":"Dear ";

If the variable visitor has the value of "PRES", then the variable
greeting will be assigned the value "Dear President " else it will be
assigned "Dear".
If the variable visitor has the value of "PRES", then the variable
greeting will be assigned the value "Dear President " else it will be
assigned "Dear"
What are JavaScript Operators?
In JavaScript, we have various types of operators.
● Arithmetic Operators

● Assignment Operators

● Comparison (Relational) Operators

● Logical Operators

● Bitwise Operators

Arithmetic Operators

Arithmetic operators perform basic arithmetic operations on the operands. Below


we have shown all arithmetic operators with their examples.

Operator Description Example

+ Add 7+3=10

– Subtract 7-3=10

* Multiply 7*3=21

/ Divide 7/3=2.34

% Modulus (Division Remainder) 7%3=1

++ Increment (Increase answer by 1) var a=7; a ++; now a= 9

– Decrement (Decrease answer by 1) var a=7; a – -; now a=5


Addition Operator
This JavaScript arithmetic operator adds two numeric operands together. The add(+) operator is
a bit different:

If one of the operands is a string, the result of the operation is a string, according to these rules:

num1 + num2

Example:

If both operands are strings, the second string is concatenated to the first.
If only one operand is a string, the other operand is converted to a string, and the
result is the concatenation of the two strings.
If single or both operands are decimal values, then it returns the decimal values.
Infinity added to –Infinity results NaN.

This behavior of add operator is a source of common mistakes, as this code snippet shows:

Syntax: You just need to write two integers. These two integers are stored in variables num1 and
num2, respectively. Then, these two numbers are added using the + operator, and the result is
printed in the console.

var num1 = 22; var


num2 = 28; var
num3 = 10.2; var
num4 = 20.6;
console.log("22 + 28 = " + num1 + num2); // 22 + 28 = 2228
console.log("22 + 28 = " + (num1 + num2)); // 22 + 28 = 50 console.log("10.2 +
20.6 = " + (num3 + num4)); // 10.2 + 20.6 = 30.8
Subtraction Operator:
This JavaScript arithmetic operator subtracts the right operand from the left.
Subtraction
Operator(-), however has only one meaning subtract. So it subtracts only. There is
no opposite
of concatenation (I think) and the subtraction operator(-) only performs subtraction
regardless
of the type of
operands.

● 'Infinity' subtracted from 'Infinity' results NaN.

Syntax: You just need to write two integers. These two integers are stored in variables num1 and
num2 respectively. Then, these two numbers are subtracted using the - operator, and the result
is printed in the console.

num1 - num2

Examples:

var num1 = 28; var


num2 = 22; var num3
= 28.50; var num4 =
22.75;
console.log("28 - 22 = " + num1 - num2); // 28 - 22 = NaN
console.log("28 - 22 = " + (num1 - num2)); // 28 - 22 = 6 console.log("28.50
- 22.75 = " + (num3 - num4)); // 28.50 -
22.75 = 5.75

Multiplication Operator:
This JavaScript arithmetic operator multiplies the two operands together. Multiplication

Operator is defined as (*) and multiply two value and return a product.
Infinity multiplied by 0 results NaN.
Infinity multiplied by Infinity results Infinity.
If Infinity is multiplied by any finite number other than 0, the result is either Infinity
or –Infinity, depending on the sign of the second operand.

Syntax: You just need to write two integers. These two integers are stored in variables num1 and
num2, respectively. Then, these two numbers are multiply using the * operator, and the result is

printed in the console.

num1 * num2

Examples:

var num1 = 28;


var num2 = 22;
console.log("28 * 22 = " + (num1 * num2)); // 28 * 22 = 616

var num1 = 28; var


num2 = -22;
console.log("28 * -22 = " + (num1 * num2)); // 28 * -22 = -616

var num1 = 'scaler'; var


num2 = 22;
console.log("scaler * 22 = " + (num1 * num2)); // scaler * 22 = NaN
Division Operator:
This JavaScript arithmetic operator divides the left operand by the value of the right operand.
Division Operator is defined as (/) and divides two value and return a quotient.

'Infinity divided by Infinity results NaN.


'Zero' divided by zero results NaN.
If a nonzero finite number is divided by zero, the result is either Infinity or
–Infinity, depending on the sign of the first operand.
If Infinity is divided by any number, the result is either Infinity or –Infinity,
depending on the sign of the second operand.

Syntax: You just need to write two integers. These two integers are stored in variables num1 and
num2, respectively. Then, these two numbers are divided using the / operator, and the result is
printed in the console.

num1 / num2

Examples:

var num1 = 28;


var num2 = 22;

console.log("28 / 22 = " + (num1 / num2)); // 28 / 22 = 1.2727272727272727

var num1 = 28; var


num2 = 0;
console.log("28 / 0 = " + (num1 / num2)); // 28 / 0 = Infinity
Modulus Operator:

This JavaScript arithmetic operator gives the remainder of the left operand when divided by the
right operand. It is also known as the Remainder operator. Modulus Operator is defined as (%)
and divides two value and return a remainder. Using the Modulus operator, we can find the
number is odd or even if we do a number modulo 2 answer is zero then it means the number is
even. If we do a number modulo 2 answer is one, then it means the number is odd.

Generally, the remainder operator is useful only when its


operands are positive integers.

Syntax: You just need to write two integers. These two integers are stored in variables num1 and
num2, respectively. Then, these two numbers use the % operator to calculate the modulus of the
If the dividend is an infinite number and the divisor is a finite number, modulus
results NaN.
If the dividend is zero and the divisor is nonzero, modulus results zero.

number, and the result is printed in the console.

num1 % num2

Examples:

var num1 = 28;


var num2 = 22;
console.log("28 % 22 = " + (num1 % num2)); // 28 % 22 = 6

var num1 = 1;
var num2 = 2;
console.log("1 % 2 = " + (num1 % num2)); // 1 % 2 = 1

123 % 10; // returns 3


Exponentiation Operator:
This JavaScript arithmetic operator gives the exponent of the left operand raised to the power of
the right operand. Exponentiation Operator is defined as (**) and raises the first operand to the
power second operand and returns an exponent.

Syntax: You just need to write two integers. These two integers are stored in variable num1 and
num2, respectively. Then, these two numbers are Exponentiation using the ** operator, and the
result is printed in the console.

num1 ** num2

Examples:

var num1 = 2;
var num2 = 2;
console.log("2 ** 2 = " + (num1 ** num2)); // 2 ** 2 = 4

Increment Operator:
This JavaScript arithmetic operator increases the value of the operand by one. Increment
Operator is defined by a double plus sign (++). This is a unary operator, x++ produces a value of
x before adding 1 to x. This is called the post-increment operator, since the value is produced,
and then the variable is incremented. On the other hand,++x produces a value of x after adding 1
to x. This is called the pre-increment operator,

Syntax: You just need to write integers. This integer is stored in variable x respectively. Then, this
numbers is incremented using the ++ operator, and the result is printed in the console.

x++ // Post-increment Operator

Examples:

++x // Pre-increment Operator


var x = 20;
x++; // x returns 21
console.log(x)
var x = 20;
var y = x++; // y is 20, x is 21
console.log(x)
console.log(y)

var x = 20;
var y = ++x; // y is 21, x is 21
console.log(x)
console.log(y)

Decrement Operator:
This JavaScript arithmetic operator decreases the value of the operand by one. Decrement

Operator is defined by a double minus sign (--). This is a unary operator, x-- produces
a value of x
before subtracting 1 to x. This is called the post-decrement operator, since the value
is
produced, and then the variable is decremented. On the other hand, --x decrements
the variable
first, and then produces the value the pre-decrement operator.

Syntax: You just need to write integers. This integer is stored in variable x
respectively. Then, this
numbers is decremented using the -- operator, and the result is printed in
the console.
x-- //Post-decrement Operator
--x //Pre-decrement Operator

Examples:

var x = 20;
x--; // x returns 19
console.log(x)

var x = 20;
var y = x--; // y is 20, x is 19
console.log(x)
console.log(y)

var x = 20;
var y = --x; // y is 19, x is 19
console.log(x)
console.log(y)

Assignment Operators

The assignment operator assigns the value, variable, and function to another

variable. Here is the list of assignment operators.

Operator Description

= Assign

+= Add and Assign

-= Subtract and Assign

*= Multiple and Assign

/= Divide and Assign

%= Modulus and Assign


Commonly Used Comparison Operators

Operator Meaning Example

== Equal to 3 == 5 // false

!= Not equal to 3 != 4 // true

=== Strictly equal to 3 === "3" // false

!== Strictly not equal to 3 !== "3" // true

> Greater than 4>4 // false

< Less than 3<3 // false

>= Greater than or equal to 4 >= 4 // true

<= Less than or equal to 3 <= 3 // true


1. JavaScript Equal To Operator
The equal to operator == evaluates to

● true if the values of the operands are equal.


● false if the values of the operands are not equal.

For example,

// same value, same type


console.log(5 == 5); // true

// same value, different type


console.log(2 == "2"); // true

// different values, same type

Note: In JavaScript, == is a comparison operator, whereas = is an assignment


operator. If you mistakenly use = instead of ==, you might get unexpected
results.
2. Not Equal To Operator
The not equal to operator != evaluates to

● true if the values of the operands aren't equal.


● false if the values of the operands are equal.

For example,

// same value, same type


console.log(2 != 2); // false

// same value, different type


console.log(2 != "2"); // false

3. Strict Equal To Operator


The strict equal to operator === evaluates to

true if both the values and the types of the operands are the same.
false if either the values or the types of the operands are not the same.

For example,

// same value, same type


console.log(2 === 2); // t//
same value, different type
Difference between the == and === operators
4. Strict Not Equal To Operator
The strict not equal to operator !== evaluates to

true if either the values or the types of the operands are not the same.
false if both the values and the types of the operands are the same.

For example,

// same value, same type


console.log(2 !== 2); // false

// same value, different type


console.log(2 !== "2"); // true

// different value, same type


5. Greater Than Operator
The greater than operator > returns

true if the value on the left is greater than the value on the right.
false if the value on the left isn't greater than the value on the right.

For example,

// left operand is greater


console.log(3 > 2); // true

// both operands are equal


console.log(4 > 4); // false

console.log(2
For example, > 5); // false

// left operand is small

6. Greater Than Or Equal To Operator


The greater than or equal to operator >= returns

true if the value on the left is greater than or equal to the value on the
right.
false if the value on the left is less than the value on the right.
7. Less Than Operator

The less than operator < returns

true if the value on the left is less than the value on the right.
false if the value on the left isn't less than the value on the right.

For example,

// left operand is smaller


console.log(2 < 5); // true

// both operands are equal


console.log(4 < 4); // false

console.log(3 < 2); // false

Run Code

8. Less Than Or Equal To Operator


The less than or equal to operator <= returns

// left operand is greater


true if the value on the left is less than or equal to the value on the right.
false if the value on the left is greater than the value on the right.

For example,

// left operand is smaller


console.log(2 <= 5); // true

// both operands are equal


console.log(4 <= 4); // true

console.log(3 <= 2); // false

Run Code

JavaScript Logical Operators


Logical operators return a boolean value by evaluating boolean expressions.
For example,

// Output: true
// left operand is greater

Run Code
const x = 5, y = 3; console.log((x <
Here, && is the logical operator AND. Since both the boolean expressions x <
6) && (y < 5))
6 and y < 5 are true, evaluating them with the && operator also results in true.

Commonly Used Logical Operators


Operator Syntax Description

&&(Logical expression1 && trueonly if both expression1and


AND) expression2 expression2are true

||(Logical expression1 || trueif either expression1or


OR) expression2 expression2is true

!(Logical !expression falseif expressionis trueand vice versa


NOT)

1. Logical AND Operator


The logical AND operator && returns true if both the expressions are true. For
example,

let x = 2;

// both expressions are true console.log((x <


4) && (4 >= x)); // true

// only one expression is true console.log((x <=


4) && (2 == 4)); // false
console.log((x > 4) && (x == 4)); // false

Run Code

Here,

// both expressions are false

● (x < 4) && (4 >= x) results in true because both expressions are true.
● (x <= 4) && (2 == 4) results in false because the expression 2 == 4

2. Logical OR Operator

The logical OR operator || returns true if at least one expression is true. For
example,
2. Logical OR Operator

The logical OR operator || returns true if at least one expression is true. For
example,

let x = 2;

// both expressions are true console.log((x <


4) || (4 >= x)); // true

// only one expression is true console.log((x <=


4) || (2 == 4)); // true

console.log((x > 4) || (x == 4)); // false

Run Code

Here,

(x < 4) || (4 >= x) results in true because both expressions are true.


(x <= 4) || (2 == 4) results in true because the expression x <= 4 is
true.

(x > 4) || (x == 4) results in false because both expressions are


false.

// both expressions are false


3. Logical NOT Operator
The logical NOT operator ! returns true if the specified expression is false
and vice versa. For example,

// NOT on true
console.log(!true); // false

// NOT on false
console.log(!false); // true

console.log(!(2 < 3)); // false

// comparison example
Here,

!true results in false because ! inverts the value of true to false.


!false results in true because ! inverts the value of false to true.
!(2 < 3) results in false because ! inverts the true value of (2 < 3) to
false.

JavaScript – Conditional Statements


JavaScript conditional statements allow you to execute specific blocks of code
based on conditions. If the condition is met, a particular block of code will run;
otherwise, another block of code will execute based on the condition.

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.
let x = 20;

if (x % 2 === 0) {

console.log("Even");

if (x % 2 !== 0) {

console.log("Odd");

};

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.

let age = 25;

if (age >= 18) {


console.log("Adult")
} else {
console.log("Not an Adult")
};

1. 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.
if (x > 0) {
console.log("Positive.");
} else if (x < 0) {
console.log("Negative.");
} else {
console.log("Zero.");
};

1. Using Switch Statement (JavaScript Switch Case)

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.
const marks = 85;

let Branch;

switch (true) {
case marks >= 90:
Branch = "Computer science engineering";
break;
case marks >= 80:
Branch = "Mechanical engineering";
break;
case marks >= 70:
Branch = "Chemical engineering";
break;
case marks >= 60:
Branch = "Electronics and communication";
break;
case marks >= 50:
Branch = "Civil engineering";
break;
default:
Branch = "Bio technology";
break;
}

console.log(`Student Branch name is : ${Branch}`);


6. Nested if…else
Nested if…else statements in JavaScript allow us to create complex conditional
logic by checking multiple conditions in a hierarchical manner. Each if statement
can have an associated else block, and within each if or else block, you can nest
another if…else statement. This nesting can continue to multiple levels, but it’s
important to maintain readability and avoid excessive complexity.

let weather = "sunny"; let


temperature = 25;

if (weather === "sunny") {


if (temperature > 30) {
console.log("It's a hot day!");

} else if (temperature > 20) {


console.log("It's a warm day.");
} else {
console.log("It's a bit cool today.");
}
} else if (weather === "rainy") {
console.log("Don't forget your umbrella!");

} else {
console.log("Check the weather forecast!");
};
TpointT
ech
TpointT
ech
TpointT
ech
Explanation

In this example

Initializes the counter variable (let i = 1).

Tests the condition(i <=5); runs while true.

Executes the loop body and increments the counter(i++).

JavaScript while Loop


In JavaScript, the while loop creates a loop that is executed as long as a specific
condition is true. JavaScript while loop will continue to run, the condition is
evaluated as false.

In the while loop, we specify the condition before the loop, and usually, some
variable is incremented or changed in the while loop body to determine when
the loop should stop.

Syntax
The syntax of while loops is as follows:

while(condition){
//code block to be executed
}

Example
let a = 0;
while(a <= 3){
console.log("Welcome to
TpoinTech"); a++;
}
Output:

Welcome to
TpoinTech
Welcome to
TpoinTech
Welcome to
TpoinTech
Welcome to
TpoinTech
Explanation

In this example, the while loop will run as long as the condition a <= 3 is true.
Since a starts at 0 and increments by 1 in each iteration, the loop will run 4
times (0, 1, 2, 3). After the 4th iteration, a will be 4, and the condition a <= 3 will
be false, so the loop will exit.

JavaScript do-while Loop


Do while loop in JavaScript is a statement used to create a loop that executes a
block of code once, then checks if a condition is true, and then repeats the loop
as long as the condition remains true.

In JavaScript, do-while loops are used when the loop body needs to be executed
at least once. The loops end when the condition is false.
Syntax

The syntax of the do-while loop is as follows:

do{
//code to execute
}while(condition)

Example
let p =
1; let q
= 1; do{
pp = p + q;
console.log(p);
q++;
}while(q<5)
Output:

2
4
7
11
Explanation

In this example, first, we initialized p and q to 1. The loop starts, and p is


updated to p + q, which is 1 + 1 = 2. The console.log(p) output 2 and q is
incremented to 2. The loop condition q < 5 is true, so the loop will repeat until q
is no longer less than 5.
JavaScript for…of loop
In JavaScript, the for…of loop iterates over an object's values rather than their
keys. With the help of this you can directly access the items as opposed to
index-reference. Some of the iterable objects are as follows:

○ An array of elements.
○ A string of characters.
○ A map of key/value pairs.

Syntax

The syntax of for…of loop is as follows:

for(variable of iterable){
//code to execute
}

Example
const items = ['BMW', 'Ferrari',
'Mustang']; for(const item of items){
console.log(item);
}
Execute Now
Output:

BMW
Ferrari
Mustang

JavaScript for…in Loop


The for…in loop in JavaScript is used to iterate over the properties of an object.
It only iterates over keys of an object that have their enumerable property set to
"true."

Syntax

The syntax of for…in loop is as follows:


for(key in object){
//code to execute
}

Example
const items = {Phone: 2, Laptop: 1, TV:
1}; for(const Appliance in items){
console.log(Appliance);
}
Output:

Pho
ne
Lapt
op
TV
And if you want to access the values:

Output:

2
1
1

JavaScript Popup Boxes

JavaScript provides various popup boxes to notify, warn, or to get input from the
user. Popup boxes prevent the user from accessing other aspects of a program
until the popup is closed, so they should not be overused.

There are three different kinds of popup methods used in JavaScript.

● Alert box
● Confirm box
● Prompt box
JavaScript Alert Box

An alert dialog box is mostly used to inform or alert the user by displaying some
messages in a small dialogue box. Following is the syntax for it:

alert("YOUR MESSAGE COMES HERE");

Let's take an example to see it in action.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Alert</h2>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
alert("I am an alert
box!");
}
</script>
</body>
</html>
JavaScript Confirm Box

A confirmation box is used to let the user make a choice. When Javascript pops up
a confirm box, the user will have to click either "OK" or "Cancel" to proceed to the
next step.

Also, based on what the user clicks on we can perform different actions. We can
specify this course of action with conditional logic.

let result = window.confirm("SOME TEXT MESSAGE");

When the user clicks on the OK button then the result variable will get the value
true and if the user clicks on the Cancel button the result variable will get the
value false.

Let's take an example and see this in action:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Confirm Box</h2>

<button onclick="myFunction()">Try it</button>

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

<script>
function
myFunction() { var
txt;
if (confirm("Press a
button!")) { txt = "You
pressed OK!";
} else {
txt = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>

JavaScript Prompt Box

Javascript Prompt Box can be used when we want to get some user input. When
Javascript displays a prompt box, the user will see a popup box with an input field
and buttons "OK" or "Cancel" to proceed after entering an input value.

Following is the syntax for the JavaScript Prompt box:

let result = prompt("SOME MESSAGE", "DEFAULT_VALUE");

Here, SOME MESSAGE is the message which is displayed in the popup box, and
DEFAULT_VALUE is the default value in the input field. The default value is an
optional field.

The value returned by the prompt depends on what exactly the user does with the
dialog.

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Confirm Box</h2>

<button onclick="myFunction()">Try it</button>

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

<script>
function
myFunction() { var
txt;
if (confirm("Press a
button!")) { txt = "You
pressed OK!";
} else {
txt = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = txt;
}

</script>

</body>
</html>

JavaScript Pop Up Boxes Use:

Now that we know about the three popup boxes that we can create and use in
JavaScript, let's cover a few usecase where we can use them.

JavaScript Alert box can be used to show any error message or any help message.
For example, if you perform form field validation, and you find some field value
incorrect, you can show an alert box with a message to inform user about the
incorrect input.

JavaScript Confirm box is a good way to confirm any important user action like if
we have a feature in our web application where upon clicking a button, we make
an AJAX call to the server to delete some data from the database, in such cases,
it's better to confirm once when the button is clicked to give the user a second
chance to confirm or cancel the request if its done by mistake. So, for important
actions, we should use the confirm popup box.

JavaScript Events
The change in the state of an object is known as an Event. In html, there are
various events which represent that some activity is performed by the user or by
the browser. When javascript code is included in HTML, js react over these events
and allow the execution. This process of reacting over the events is called Event
Handling. Thus, js handles the HTML events via Event Handlers.

For example, when a user clicks over the browser, add js code, which will execute
the task to be performed on the event.

Mouse events:

click onclick When mouse click on an


element

mouseover onmouseover When the cursor of


the mouse comes
over the element

mouseout onmouseout When the cursor of the


mouse leaves an element
mousedown onmousedown When the mouse button
is pressed over the
element

mouseup onmouseup When the mouse button


is released over the
element

mousemove onmousemove When the mouse


movement takes
place.

Keyboard events:

Event Performed Event Handler Description

Keydown & Keyup onkeydown & onkeyup When the user press and
then release the key

Form events:

Event Performed Event Handler Descriptio


n
focus onfocus When the user focuses on
an element

submit onsubmit When the user


submits the form

blur onblur When the focus is away


from a form element

change onchange When the user modifies


or changes the value of a
form element

Window/Document events

Event Performed Event Handler Description

load onload When the browser


finishes the loading of
the page

unload onunload When the visitor


leaves the current
webpage, the browser
unloads it

resize onresize When the visitor


resizes the window of
the browser
reset onreset When the window size is
resized

scroll onscroll When the visitor scrolls a


scrollable area

Let's discuss some examples over events and their handlers.

Click Event
<html>
<head> Javascript Events </head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function clickevent()
{
document.write("This is Tpoint Tech");
}
//-->
</script>
<form>
<input type="button" onclick="clickevent()" value="Who's this?"/>
</form>
</body>
</html>

Explanation:

In the above given example, we have created a function "clickevent" which is


called by using the "onclick" event. When a user will click on this button then this
function will be called, function will return a string "This is Tpoint Tech" and
"document.write" function will help to write the returned string on the document.

MouseOver Event
<head>
<h1> Javascript Events </h1>
</head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function mouseoverevent()
{
alert("This is Tpoint Tech");
}
//-->
</script>
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
</body>
</html>

Explanation:

In the above given example, we have created a function "mouseoverevent" which


is called by using the "onmouseover" event. When a user will mouser over a <p>
text then this function will be called and an alert box will be displayed. We can
reuse the mouseoverevent function as many as need in our program, so it will
save memory.

Focus Event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
<!--
function focusevent()
{
document.getElementById("input1").style.background=" aqua";
}
</script>
</body>
</html>

Explanation:

In the above given example, we have created a function "focusevent" which is


called by using the "onfocus" event. When a user will focus on a text field then
this function will be called and a text field background color will be changed.

JavaScript - Keyboard Events


The keyboard events in JavaScript provide a way to interact with a web page or
application based on the user's keyboard input. These events allow developers to
capture and respond to various keyboard actions, such as key presses, key
releases, and character inputs. The primary keyboard events in JavaScript include
keydown, keypress, and keyup.

Common Keyboard Events


Keydown Event − When a key on the keyboard is pressed down, it triggers
the keydown event. This event equips developers with information about
the specific key that was pressed: this includes its code and an indicator of
whether certain modifier keys such as Shift, Ctrl, or Alt were also
depressed.
Keypress Event − The keypress event triggers when a user types an actual
character. Non-character keys, such as Shift or Ctrl, do not activate this
event. Developers frequently utilize it to capture user input for form fields
or create interactive typing features.
Keyup Event − Upon the release of a previously pressed key, the system
initiates the firing of a keyup event; this particular event proves beneficial
in tracking specific keys' releases and subsequently implementing actions,
thereby creating an interactive user experience.
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
<!--
function keydownevent()
{
document.getElementById("input1");
alert("Pressed a key");
}
//-->
</script>
</body>
</html>

Explanation:

In the above given example, we have created a function "keydownevent" which is


called by using the "onkeydown" event. When a user will focus on a text field then
this function will be called and a alert box will be displayed.

Example: Keypress Event


In this example, the keypress event is utilized to capture a typed character. When
a character is typed, the event listener triggers, and the character is displayed in
the HTML element with the id "output".

<!DOCTYPE html>

<html>

<body>

<h3>Type a character</h3>

<div id="output"></div>

<script>

document.addEventListener('keypress', function (event) {


document.getElementById('output').innerHTML =

"Character pressed: " + event.key;

});

</script>

</body>

</html>

Example: Keyup Event


The keyup event is showcased in this example. It captures the event when a key is
released after being pressed. The released key is then displayed on screen.

<!DOCTYPE html>

<html>

<body>

<h3>Press and Release a key</h3>

<div id="output"></div>

<script>

document.addEventListener('keyup', function (event) {

document.getElementById('output').innerHTML =

"Key released: " + event.key;

});

</script>
</body>

</html>

Form Events

The form events in JavaScript are events that are associated with HTML forms.
These events are triggered by user actions when interacting with form elements
like text fields, buttons, checkboxes, etc. Form events allow you to execute
JavaScript code in response to these actions, enabling you to validate form data,
perform actions on form submission or reset, and enhance the user experience.

JavaScript form events are hooked onto the elements in the Document Object
Model also known as DOM where by default the bubbling propagation is used i.e.
from bottom (children) to top(parent).

List of Common Form Events

Here are some common form events:

Form Description
Event
onsub Triggered when a form is submitted. It's often used for form validation
m it before data is sent to the server.
onrese Triggered when the form is reset, allowing you to perform actions
t when the user resets the form.
onchan Triggered when the value of a form element (input, select, textarea)
ge changes. Commonly used for user input validation or dynamic updates.

oninpu Triggered immediately when the value of an input element changes,


t allowing for real-time handling of user input.
onfocu Triggered when an element receives focus, such as when a user clicks
s or tabs into an input field. Useful for providing feedback or
enhancing the user experience.
</script>

</body>

</html>

Example: The onsubmit Event

The following example highlights the onsubmit event's functionality upon form
submission. The form features a username field and password field; both must be
filled for successful validation when invoking the validateForm function. Upon
passing this validation, submitting the form will trigger display of a confirmation
message.

<!DOCTYPE html>

<html>

<body>

<form onsubmit="return validateForm()">

<label for="username">Username:</label>

<input type="text" id="username" name="username" required>

<label for="password">Password:</label>

<input type="password" id="password" name="password"


required>

<br/>

<input type="submit" value="Submit">

</form>

<script>

function validateForm() {
var username =
document.getElementById('username').value;

var password =
document.getElementById('password').value;

// Perform validation

if (username === "" || password === "") { alert("Please fill in all

fields");

return false; // Prevent form submission

alert("Form submitted! Username


is:"+username+",Password is:"+password);

return true; // Allow form submission

</script>

</body>

</html>

Example: The onreset event

In this demonstration, we observe the onreset event in action: it triggers upon the
user's click of the "Reset" button within a form. The resetForm function once
invoked, clears the form content filled by user and then displays an alert to
confirm successful reset of said form.

<!DOCTYPE html>
<html>

<body>

<form onreset="resetForm()">

<label for="email">Email:</label>

<input type="email" id="email" name="email" required

<input type="reset" value="Reset">

</form>

<script>

function resetForm() {

// Perform actions when the form is reset alert("Form

has been reset!");

</script>

</body>

</html>

Example: onfocus and onblur Events

The onfocus and onblur events merge in this example. The user's focus on the
input field triggers a call to the handleFocus function, which then logs a message
into the console. In contrast, when clicks outside of or tabs away from said input
field this action triggers execution of another function called handleBlur that
subsequently records an alternative message within that same console log.
<!DOCTYPE html>

<html>

<body>

<label for="name">Name:</label>

<input type="text" id="name" onfocus="handleFocus()"


onblur="handleBlur()">

<p id= "output"></p>

<script>

const output = document.getElementById('output'); function

handleFocus() {

// Perform actions when the input gets focus

output.innerHTML += "Input has focus" + "<br>";

function handleBlur() {

// Perform actions when the input loses focus

output.innerHTML += "Input lost focus" + "<br>";

</script>

</body>

</html>

JavaScript - Window/Document Events


JavaScript window events are actions that occur when the user does something
affecting the entire browser window, like loading, resizing, closing, or moving the
window. The most common window event is simply loading the window by
opening a particular web page. This event is handled by the onload event handler.

Window Events
At the browser level, window events happen and hold association with the
window object; this global object represents the web browser's window.
Frequently employed to oversee the overall state of a browser window or
manage global interactions are these types of events.

loaded successfully" and "document.write" function will help to write the returned
string on the document.

Event Description
Name
load Triggered when the entire web page, including all its resources, has
finished loading.
unload Fired when the user is leaving the page or closing the browser
window or tab.
resize Activated when the size of the browser window is changed.

scroll Fired when the user scrolls the page.

Example: Demonstrating LOAD Events

Load event
<html>
<head>Javascript Events</head>
</br>
<body onload="window.alert('Page successfully loaded');">
<script>
<!--
document.write("The page is loaded successfully");
//-->
</script>
</body>
</html>

Explanation:
In the above example, we created an "onload" event on the html's <body> tag. When a HTML
body will be loaded then a function will return a string "The page is

JavaScript Arrays

In JavaScript, an array is a collection of multiple values stored at different memory


locations but sharing the same name. You can access the values in an array by
using the indexes within square brackets, starting from 0 up to the length of the
array minus 1([0]…[n-1]).

The syntax of arrays in JavaScript is as follows:

const array_name = [item1, item2,…..];


Example
const age = [20, 22, 21, 10, 12];
console.log(age);
Output:

[ 20, 22, 21, 10, 12]

How to Create Arrays in JavaScript?


There are 3 ways to create an array in JavaScript. Such as:

○ Array Literals
○ Using new keyword
○ Array Constructor

Array Literal
An array literal is a list of zero or more expressions, each of which represents an
array element, enclosed in square brackets([]).

Syntax

The array can be created with an array literal by using the syntax below.

var arrayname=[value1, value2. valuen];


Example
let country = [ "India", "Australia", "England" ]; for (let i = 0;

i<country.length; i++ ){

console.log( country[i]);
}
Output:

India
Australia
England

Using a new keyword


With the use of a new keyword in JavaScript, you can easily create an array.

Syntax

var array_name = new Array ();


Example
let num;
let country = new Array ();
country[0] = "Japan";
country[1] = "Spain";
country[2] = "Germany";
for ( num = 0; num<country.length; num++ )
{
console.log( country[num]);
}
Output:

Japan
Spain
Germa
ny

Array Constructor
You can create an array instance by passing arguments into a constructor.

Example
let employee = new Array("Rohit", "Vivek",
"Jhon"); for (let i=0;i<employee.length;i++){
console.log(employee[i]);

}
Output:

Rohit
Vivek
Jhon

Basic Operations on JavaScript Arrays


In JavaScript, arrays offer several operations for managing and manipulating
data efficiently.

Accessing Elements of an Array


In JavaScript, when you want to access an element at a specific index in an array,
you can use brackets[] with the index number.

Example
let cars = ["BMW", "Buggati", "Skyline"];
console.log(cars[1]);
Output:

Buggati

Accessing the First Element of an Array


By using index 0 you can access the first element of an array.

Example
let cars = ["BMW", "Buggati", "Skyline"];
console.log(cars[0]);
Output:

BMW

Accessing the Last Element of an Array


By using the index length - 1, you can access the last element of an array.

Example
let cars = ["BMW", "Buggati",
"Skyline"]; let last = cars[cars.length-
1]; console.log(last);
Output:

Skyline

Modifying the Array Elements


By assigning a new value to a specific index, you can modify elements in an array.

Example
let cars = ["BMW", "Buggati", "Skyline"];
cars[1] = "Ferrari";
console.log(cars);
Output:

[ 'BMW', 'Ferrari', 'Skyline' ]


Adding Elements to the Array
By using the push() Method, you can add elements to the end of an array.

Example
let cars = ["BMW", "Buggati", "Skyline"];
cars.push("GTR");
console.log(cars);
Output:

[ 'BMW', 'Buggati', 'Skyline', 'GTR' ]

Removing Elements from an Array


By using methods like pop(), shift(), or splice(), you can remove elements from an
array.

Example
let cars = ["BMW", "Buggati", "Skyline"];
cars.pop(); // removes the last element
console.log(cars);
Output:

[ 'BMW', 'Buggati' ]

JavaScript Array unshift() method


The JavaScript array unshift() method adds one or more elements in the
beginning of the given array and returns the updated array. This method changes
the length of the original array.

Syntax
The unshift() method is represented by the following syntax:

array. unshift(element1,element2,. ,elementn)

Parameter
element1,element2, ... ,elementn - The elements to be added.

Return
The original array with added elements.

JavaScript Array unshift() method example


Let's see some examples of unshift() method.

Example 1
Here, we will add an element in the given array.

<script>
var
arr=["AngularJS","Node.js"];
var result=arr.unshift("JQuery");
document.writeln(arr);
</script>
Output:

JQuery,AngularJS,Node.js
JavaScript Array Methods
Let's see the list of JavaScript array methods with their description.

Methods Description

concat() It returns a new array object that


contains two or more merged arrays.

copywithin() It copies the part of the given array


with its own elements and returns
the modified array.

entries() It creates an iterator object and a loop


that iterates over each key/value pair.

every() It determines whether all the


elements of an array are satisfying
the provided function conditions.

flat() It creates a new array carrying sub-


array elements concatenated
recursively till the specified depth.

flatMap() It maps all array elements via


mapping function, then flattens the
result into a new array.
fill() It fills elements into an array with static
values.

from() It creates a new array carrying the exact


copy of another array element.

filter() It returns the new array containing


the elements that pass the
provided function conditions.

find() It returns the value of the first


element in the given array that
satisfies the specified condition.

findIndex() It returns the index value of the first


element in the given array that
satisfies the specified condition.

forEach() It invokes the provided function once


for each element of an array.

includes() It checks whether the given


array contains the specified
element.

indexOf() It searches the specified element in


the given array and returns the index
of the first match.

isArray() It tests if the passed value ia an array.


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

keys() It creates an iterator object that


contains only the keys of the array,
then loops through these keys.

lastIndexOf() It searches the specified element in


the given array and returns the index
of the last match.

map() It calls the specified function for


every array element and returns the
new array

of() It creates a new array from a


variable number of arguments,
holding any type of argument.

pop() It removes and returns the last


element of an array.

push() It adds one or more elements to the


end of an array.

reverse() It reverses the elements of given array.

reduce(function, initial) It executes a provided function for each


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

some() It determines if any element of the


array passes the test of the
implemented function.

shift() It removes and returns the first


element of an array.

slice() It returns a new array containing


the copy of the part of the given
array.

sort() It returns the element of the given


array in a sorted order.

splice() It add/remove elements to/from the


given array.

toLocaleString() It returns a string containing all the


elements of a specified array.

toString() It converts the elements of a


specified array into string form,
without affecting the original array.

unshift() It adds one or more elements in the


beginning of the given array.
values() It creates a new iterator object carrying
values for each index in the array.

Objects in Javascript
An object in JavaScript is a data structure used to store related data collections.
It stores data as key-value pairs, where each key is a unique identifier for the
associated value. Objects are dynamic, which means the properties can be
added, modified, or deleted at runtime.

There are two primary ways to create an object in JavaScript: Object Literal
and Object Constructor.

fi. Creation Using Object Literal

The object literal syntax allows you to define and initialize an object with curly
braces {}, setting properties as key-value pairs.

let obj = {
name: "Sourav",
age: 23,
job: "Developer"
};
console.log(obj);

Output
{ name: 'Sourav', age: 23, job: 'Developer' }

3. Creation Using new Object() Constructor

let obj = new Object();


obj.name= "Sourav",
obj.age= 23, obj.job=
"Developer"

console.log(obj);

Output
{ name: 'Sourav', age: 23, job: 'Developer' }

Basic Operations on JavaScript Objects

fi. Accessing Object Properties

You can access an object’s properties using either dot notation or bracket
notation

let obj = { name: "Sourav", age: 23 };

// Using Dot Notation

// Using Bracket Notation


console.log(obj["age"]);

console.log(obj.name);
Output
Sourav
23

2. Modifying Object Properties

Properties in an object can be modified by reassigning their values.

let obj = { name: "Sourav", age: 22 }; console.log(obj);


obj.age = 23;
console.log(obj);

Output
{ name: 'Sourav', age: 22 }
{ name: 'Sourav', age: 23 }

3. Adding Properties to an Object

You can dynamically add new properties to an object using dot or bracket
notation.

let obj = { model: "Tesla" }; obj.color


= "Red";

console.log(obj);

Output
{ model: 'Tesla', color: 'Red' }

4. Removing Properties from an Object

The delete operator removes properties from an object.

let obj = { model: "Tesla", color: "Red" };


delete obj.color;

console.log(obj);
Output
{ model: 'Tesla' }

5. Checking if a Property Exists

You can check if an object has a property using the in operator or


hasOwnProperty() method.

let obj = { model: "Tesla" };


console.log("color" in obj);
console.log(obj.hasOwnProperty("model"));

Output
false true

6. Iterating Through Object Properties

Use for…in loop to iterate through the properties of an object.

let obj = { name: "Sourav", age: 23 };


for (let key in obj) {
console.log(key +
": " + obj[key]);
}

Output name:
Sourav age: 23

7. Merging Objects

Objects can be merged using Object.assign() or the spread syntax { …obj1,


…obj2 }.

let obj1 = { name: "Sourav" };


let obj2 = { age: 23};
let obj3 = { ...obj1, ...obj2 };
console.log(obj3);

Output
{ name: 'Sourav', age: 23 }

8. Object Length

You can find the number of properties in an object using Object.keys().

let obj = { name: "Sourav", age: 23 }; console.log(Object.keys(obj).length);

Output
2

Recognizing a JavaScript Object


To check if a value is an object, use typeof and verify it’s not null.

let obj = { name: "Sourav" };

console.log(typeof obj === "object" && obj !== null);

Output
true

Common Mistakes with JavaScript Objects


Let’s dive into the differences between {} and new Object() in JavaScript, as this is
an important concept when working with objects.

In JavaScript, there are two main ways to create objects


● Using Object Literal Syntax ({}): This is the most common and

simple way to create objects.

● Using the Object Constructor (new Object()): This uses

JavaScript’s built-in Object constructor to create objects.

// Object literal
const obj1 = { key: "value" };

// Object constructor const


obj2 = new Object();
obj2.key = "value";

console.log(obj1); console.log(obj2);

Output
{ key: 'value' }
{ key: 'value' }

At first glance, both approaches seem to achieve the same result. However,
there are significant differences to understand.

Key Differences Between {} and new Object()

new Object() (Object


Feature {}(Object Literal)
Constructor)
More concise and
Ease of Use Less commonly used.
readable.

Faster and Slightly slower due to


Performance
more the constructor call.
efficient.

Prototypal Directly inherits from Same, but adds an extra


Inheritance Object.prototype. layer of abstraction.

Literal syntax is
Useful only in
Customization sufficient for most use
rare
cases.
scenarios.

Why Is {} Preferred?

● Simpler Syntax: The literal form is cleaner and easier to read.

● Performance: {} skips the overhead of calling a constructor function.

● Fewer Errors: Using new Object() may unintentionally override the

constructor if the environment changes.

Functions in JavaScript
Functions in JavaScript are reusable blocks of code designed to perform specific
tasks. They allow you to organize, reuse, and modularize code. It can take inputs,
perform actions, and return outputs.In JavaScript, a function is a reusable block
of code that can be defined and then executed whenever needed.
Functions are one of the fundamental building blocks of JavaScript and play a

crucial role in structuring and organizing code.

function sum(x, y) {
return x + y;
}
console.log(sum(6, 9));
9. Checking if a Property Exists

You can check if an object has a property using the in operator or


hasOwnProperty() method.

let obj = { model: "Tesla" };


console.log("color" in obj);
console.log(obj.hasOwnProperty("model"));

Output
false true

10. Iterating Through Object Properties

Use for…in loop to iterate through the properties of an object.

let obj = { name: "Sourav", age: 23 };


for (let key in obj) {
console.log(key +
": " + obj[key]);
}

Output name:
Sourav age: 23

11. Merging Objects

Objects can be merged using Object.assign() or the spread syntax { …obj1,


…obj2 }.

let obj1 = { name: "Sourav" };


let obj2 = { age: 23};
let obj3 = { ...obj1, ...obj2 };
console.log(obj3);

Output
{ name: 'Sourav', age: 23 }

12. Object Length

You can find the number of properties in an object using Object.keys().

let obj = { name: "Sourav", age: 23 }; console.log(Object.keys(obj).length);

Output
2

Recognizing a JavaScript Object


To check if a value is an object, use typeof and verify it’s not null.

let obj = { name: "Sourav" };

console.log(typeof obj === "object" && obj !== null);

Output
true

Common Mistakes with JavaScript Objects


Let’s dive into the differences between {} and new Object() in JavaScript, as this is
an important concept when working with objects.

In JavaScript, there are two main ways to create objects


● Using Object Literal Syntax ({}): This is the most common and

simple way to create objects.

● Using the Object Constructor (new Object()): This uses

JavaScript’s built-in Object constructor to create objects.

// Object literal
const obj1 = { key: "value" };

// Object constructor const


obj2 = new Object();
obj2.key = "value";

console.log(obj1); console.log(obj2);

Output
{ key: 'value' }
{ key: 'value' }

At first glance, both approaches seem to achieve the same result. However,
there are significant differences to understand.

Key Differences Between {} and new Object()

new Object() (Object


Feature {}(Object Literal)
Constructor)
More concise and
Ease of Use Less commonly used.
readable.

Faster and Slightly slower due to


Performance
more the constructor call.
efficient.

Prototypal Directly inherits from Same, but adds an extra


Inheritance Object.prototype. layer of abstraction.

Literal syntax is
Useful only in
Customization sufficient for most use
rare
cases.
scenarios.

Why Is {} Preferred?

● Simpler Syntax: The literal form is cleaner and easier to read.

● Performance: {} skips the overhead of calling a constructor function.

● Fewer Errors: Using new Object() may unintentionally override the

constructor if the environment changes.

Functions in JavaScript
Functions in JavaScript are reusable blocks of code designed to perform specific
tasks. They allow you to organize, reuse, and modularize code. It can take inputs,
perform actions, and return outputs.In JavaScript, a function is a reusable block
of code that can be defined and then executed whenever needed.
Functions are one of the fundamental building blocks of JavaScript and play a

crucial role in structuring and organizing code.

function sum(x, y) {
return x + y;
}
console.log(sum(6, 9));
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.

// Function Definition
function welcomeMsg(name) {
return ("Hello " + name + " welcome to LNCT");
}
let nameVal = "User";
// calling the function
console.log(welcomeMsg(nameVal));

Why Functions?
● Functions can be used multiple times, reducing redundancy.

● Break down complex problems into manageable pieces.

● Manage complexity by hiding implementation details.

● Can call themselves to solve problems recursively.

Key Characteristics of Functions

● Parameters and Arguments: Functions can accept parameters

(placeholders) and be called with arguments (values).

● Return Values: Functions can return a value using the return

keyword.

● Default Parameters: Default values can be assigned to function

parameters.

Advantages of Functions in JavaScript


● Reusability: Write code once and use it multiple times.

● Modularity: Break complex problems into smaller, manageable

pieces.

● Improved Readability: Functions make code easier to understand.

● Maintainability: Changes can be made in one place without

affecting the entire codebase.

Choosing the Right Function Type

● Use function declarations for regular reusable functions.

● Use arrow functions for concise, one-line functions.

● Use IIFE for code that runs immediately.

● Use callback functions for asynchronous operations like API calls.

● Use pure functions for predictable behavior without side effects.

Arrow functions in JavaScript

An arrow function is a shorter syntax for writing functions in JavaScript.

Introduced in ES6, arrow functions allow for a more concise and readable code,

especially in cases of small functions. Unlike regular functions, arrow functions

don’t have their own this, but instead, inherit it from the surrounding context.
● Arrow functions are written with the => symbol, which makes them

compact.

● They don’t have their own this. They inherit this from the

surrounding context.

● For functions with a single expression, the return is implicit,

making the code more concise.

● Arrow functions do not have access to the arguments object, which

is available in regular functions.

const add = (a, b) => a + b;

console.log(add(5, 3));

Output 8

JavaScript Callbacks
In JavaScript, callbacks play an essential role in handling asynchronous tasks like
reading files, making API requests, and executing code after certain events. If
you’ve ever heard the phrase “I will call back later!”, that’s exactly how
callbacks work.

What is a Callback Function?


A callback function is a function that is passed as an argument to another
function and executed later.

● A function can accept another function as a parameter.


● Callbacks allow one function to call another at a later time.

● A callback function can execute after another function has finished.

function greet(name, callback) {


console.log("Hello, " + name);
callback();
}

function sayBye() {
console.log("Goodbye!");
}

greet("Ajay", sayBye);

Output Hello,
Ajay Goodbye!

JavaScript Anonymous Functions

An anonymous function is simply a function that does not have a name. Unlike

named functions, which are declared with a name for easy reference,

anonymous functions are usually created for specific tasks and are often assigned

to variables or used as arguments for other functions.

const greet = function () {


console.log("Welcome toLNCT!");
};

greet();Example 2: Passing arguments to the anonymous function.


const greet = function( str ) {
console.log("Welcome to ", str);
};

greet("LNCT!");

Arrow functions

ES6 introduced a new and shorter way of declaring an anonymous function,

which is known as Arrow Functions. In an Arrow function, everything remains

the same, except here we don’t need the function keyword also. Here, we define

the function by a single parenthesis and then ‘=>’ followed by the function body.

Example 5: This is an example of anonymous function with arrow function.

const greet = () => {


console.log("Welcome to LNCT!");
}
greet();
Pure Functions

Pure functions return the same output for the same inputs and do not produce

side effects. They do not modify state outside their scope, such as modifying global

variables, changing the state of objects passed as arguments, or performing I/O

operations.

function pureAdd(a, b) {
return a + b;
}
console.log(pureAdd(2, 3));

Output

USING JAVA SCRIPT IN REAL TIME RELATED EXAMPLE-

1. Client-Side Web Development


The most common example describing what JavaScript is used for involves delivering
an interactive user experience (UX). JavaScript is a paramount technology for front-end
development.

You can thank JavaScript for the way you navigate the web by using a drop-down
arrow to scroll to the bottom of a page, the
auto-suggestions in search, and any live content updates.

Before JavaScript, everything had to be static, but now we can see some of the
most complex content that responds to a variety of interactions. Zooming, videos,
audio, and anything else that requires a change without the whole page
refreshing is thanks to JavaScript.

2. Server-Side Development
Initially, JavaScript was only used in web browsers, but with Node.js, it is now
possible – and very much expected – to write and execute JavaScript on the
server side.

Server-side scripting carries the imminent advantage of allowing content to load


without the concern for browser capacity. Decreased load times or faster
responses can lead to improved SEO thanks to the increase in user satisfaction.

This is yet another example of what JavaScript is used for. Using JavaScript’s
runtime environment, Node.js, developers can create scalable and high-
performance web servers, manage databases, and handle authentication
processes. All of this makes it a viable option in 2025.

3. Mobile App Development


JavaScript has several different frameworks for developing web and mobile apps,
including React Native, Ionic, and Angular. All these frameworks extend tooling to
simplify development depending on what JavaScript is used for in each specific
framework.

Facebook is one popular company that uses JavaScript to power its online
community. React, and the corresponding React Native are two JavaScript
frameworks built by Facebook. By using both of these, you can use a single code-
base across iOS and Android apps instead of writing entirely separate code for
each.

This is one of many reasons why companies like Netflix and Uber also like to
leverage JavaScript for their front-end interactions. The result is that these
companies have apps that are responsive and dynamic, perfect for their needs.

4. Game Development
JavaScript can be utilized to develop games for web browsers. GitHub features a
collection of game engines, many of them employing HTML5 as well.

JavaScript is even being used in the virtual reality industry with the help of the
WebXR Device API, allowing developers to create immersive gaming experiences.
Many modern browser-based games on the market at the moment rely on
JavaScript for real-time rendering and physics-based interactions.
5. Desktop Application Development
We have already discussed how JavaScript can be used in both mobile and web
development. But with the rise of tools and frameworks like Electron.js,
developers can now build desktop applications using JavaScript, HTML, and CSS,
providing
cross-platform compatibility.

This means that a lot of browser-based apps can maintain consistency when their
respective app is installed on a phone or computer.

Well-known applications such as Slack, Visual Studio Code, and Discord are built
using Electron, leveraging JavaScript’s efficiency and flexibility to deliver seamless
user experiences across operating systems.
6. AI & Machine Learning Applications
JavaScript has libraries that support development for AI-related projects as well.
Tensorflow.js, for instance, is a JavaScript library for machine learning. You can
build and train machine learning models using the library.

Popular uses for AI applications that have been built with JavaScript can vary, but
some popular examples we have come across here at Trio include apps or
components of apps that take care of image recognition, chatbot development,
and predictive analytics.

JavaScript also lets developers integrate machine learning into their web and
mobile apps. This has various uses in dealing with big data.

jQuery

jQuery is a fast, small, cross-platform and feature-rich JavaScript library. It is


designed to simplify the client-side scripting of HTML. It makes things like HTML
document traversal and manipulation, animation, event handling, and AJAX very
simple with an easy-to-use API that works on a lot of different type of browsers.

The main purpose of jQuery is to provide an easy way to use JavaScript on your
website to make it more interactive and attractive. It is also used to add
animation.

What is jQuery
jQuery is a small, light-weight and fast JavaScript library. It is cross-platform and
supports different types of browsers. It is also referred as ?write less do more?
because it takes a lot of common tasks that requires many lines of JavaScript code
to accomplish, and binds them into methods that can be called with a single line
of code whenever needed. It is also very useful to simplify a lot of the complicated
things from JavaScript, like AJAX calls and DOM manipulation.

○ jQuery is a small, fast and lightweight JavaScript library.


○ jQuery is platform-independent.
○ jQuery means "write less do more".
○ jQuery simplifies AJAX call and DOM manipulation.

why jQuery is required


Sometimes, a question can arise that what is the need of jQuery or what
difference it makes on bringing jQuery instead of AJAX/ JavaScript? If jQuery is the
replacement of AJAX and JavaScript? For all these questions, you can state the
following answers.

○ It is very fast and extensible.


○ It facilitates the users to write UI related function codes in minimum
possible lines.
○ It improves the performance of an application.
○ Browser's compatible web applications can be developed.
○ It uses mostly new features of new browsers.
So, you can say that out of the lot of JavaScript frameworks, jQuery is the most
popular and the most extendable. Many of the biggest companies on the web use
jQuery.

Some of these companies are:

○ Microsoft
○ Google
○ IBM
○ Netflix

What should you know before starting to learn jQuery?


It is always advised to a fresher to learn the basics of web designing before
starting to learn jQuery. He should learn HTML, CSS and JavaScript first. But, if you
belong to a technical background, it is up to you.

If you are a fresher and want to study these subjects first.

Features-

Here's a list of jQuery's key features:


DOM Manipulation:
jQuery simplifies the process of selecting and manipulating HTML
elements, making it easier to modify the structure, content, and attributes
of web pages.
Event Handling:
It provides a straightforward way to handle events like clicks, mouseovers,
and form submissions, enabling dynamic and interactive web applications.
Effects and Animations:
jQuery offers a range of built-in effects and animations, such as fading,
sliding, and hiding elements, allowing developers to add visual appeal and
interactivity to their websites.
AJAX Support:
It simplifies asynchronous communication with servers, allowing web pages
to update content without requiring a full page reload.
Utilities:
jQuery includes a collection of utility functions for common tasks like array
manipulation, string processing, and type checking, making it easier to
write efficient and concise code.
Cross-browser Compatibility:
It handles cross-browser inconsistencies, ensuring that web applications
work consistently across different browsers and platforms.
Lightweight:
jQuery has a small file size, which helps reduce page load times and
improve website performance.
Extensibility:
It can be extended with plugins, allowing developers to add custom
functionality and tailor the library to their specific needs.
CSS Manipulation:
jQuery enables easy modification of CSS styles, allowing developers to dynamically
change the appearance of web pages.
JSON Parsing:
It provides built-in support for parsing JSON data, making it easier to work
with data from APIs and other sources.

Jquery installing

r simple step-by-step guide on how to install and use jQuery, depending on your
setup:

For a regular HTML website (no special tools)

Step 1: Use a CDN (Quickest Way)

Just copy and paste this inside your HTML file:


<!DOCTYPE html>
<html>
<head>
<title>My jQuery Page</title>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>

<p>Click me!</p>

<script>
$(document).ready(function(){
$('p').click(function(){
alert("You clicked the paragraph!");
});
});
</script>

</body>
</html>

That’s it! You’re using jQuery!

For a project with Node.js (npm install)

If you're using a development environment like Node.js, follow these steps:

Step 1: Initialize your project


npm init -y

Step 2: Install jQuery


npm install jquery

Step 3: Use jQuery in your JavaScript


// main.js
import $ from 'jquery';

$(document).ready(function() {
console.log("Hello from jQuery!");

});

jQuery Syntax
The jQuery syntax is tailor-made for selecting HTML elements and performing
some action on the element(s).

Basic syntax is: $(selector).action()

● A $ sign to define/access jQuery


● A (selector) to "query (or find)" HTML elements
● A jQuery action() to be performed on the element(s)

Examples:

$(this).hide() - hides the current element.

$("p").hide() - hides all <p> elements.

$(".test").hide() - hides all elements with class="test".

$("#test").hide() - hides the element with id="test".


Following is the basic syntax for selecting HTML elements and then performing
some action on the selected element(s):

$(document).ready(function(){
$(selector).action()
});

Any jQuery statement starts with a dollar sign $ and then we put a selector inside
the braces (). This syntax $(selector) is enough to return the selected HTML
elements, but if you have to perform any action on the selected element(s) then
action() part is required.

The factory function $() is a synonym of jQuery() function. So in case you are using
any other JavaScript library where $ sign is conflicting with some

thing else then you can replace $ sign by jQuery name and you can use function
jQuery() instead of $().

Examples
Below are few examples to illustrate the basic jQuery Syntax. Following example
will select all the <p> elements from an HTML document and will hide those
elements. jQuery code:

<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script
src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></sc ript>
<script>
$(document).ready(function() {
$("p").hide()
});
</script>
</head>
<body>
<h1>jQuery Basic Syntax</h1>
<p>This is p tag</p>
<p>This is another p tag</p>
<span>This is span tag</span>
<div>This is div tag</div>
</body>
</html>
Some essential functions of jQuery for web designing
As a beginner web developer, you must know its basic functions in web
development. It will make it easier to use JavaScript in web page development.
Also, if you plan to enrol on graphics and animation courses, you can learn about
jQuery functions from there. Here, we will list some most popular jQuery
functions that are widely used in web page designing-
Hide function
The hide function of jQuery helps you hide any selected HTML element with
simple steps. All you need to do is to call the function and follow the process. As
a result, when you script the hide function for a selected element, it hides the
element from your page. You can learn more about jQuery functions and web
design from Moople Web Design Institute.
Show function

This jQuery function works opposite to the hide function. It lets you display or
show the hidden HTML element using the hide function. So, you must learn the
hide function first to learn the show function. What you will show is simple if all
your HTML elements are already displayed on the web page.
Therefore, before you apply the show function on any HTML element of the web
page, you must use the hide function on the same HTML element.
slideUp function
The slide Up function of jQuery also lets the developers hide any selected
HTML element without using the hide function. The slide Up function is a cool
alternative to the hide function to help you hide any selected HTML element.
The function helps to slide the selected HTML element up and remove it
slowly.
The most interesting feature of this jQuery function is that it helps you
control the sliding speed, making it most accessible and effective.
slideDown function
Like the slide Up (an alternative to hide), the slide Down function is an alternative
to the show function. The slide Down function helps show the selected HTML
element. The slide Down function allows you to show your selected HTML
element on the web page, similar to the show function. But it works more
effectively as you can control how the HTML element appears on your webpage.
The graphics and animation courses can help you learn about jQuery and other
programming languages. Also, Moople can offer quality web designing and
animation courses in Kolkata.
Toggle function
The toggle function is another essential function of jQuery for web designing. The
toggle function is a versatile function that can do the task of both hide and show
functions. The toggle function is very useful as it uses a single element to hide or
show an HTML element. It can be a great option to give your users both controls
of showing and hiding a specific element. At Moople Web Design Institute, you
can learn more about jQuery functions and other web design elements.
SlideToggle function
Another versatile jQuery function useful for web designing is the Slide Toggle
function. This toggle function works on the selected HTML element for both slide
Up and slide Down functions. It works similarly to the toggle function comprising
the hide and show function. The only difference is that it comprises the work of
slide Up and slide Down. So, the Slide Toggle function can do the work of both
the slide Up and slide Down functions on a selected HTML element during the
sliding of your webpage.

Key jQuery Functions for UI Design:

DOM Manipulation:
jQuery simplifies selecting and manipulating HTML elements.
● $("#elementId"): Selects an element by its ID.
● $(".className"): Selects elements by class name.
● $("element"): Selects elements by tag name.
● .hide(): Hides the selected element(s).
● .show(): Shows the selected element(s).
● .slideUp(): Hides the selected element(s) with a slide-up animation.
● .slideDown(): Shows the selected element(s) with a slide-down animation.
● .fadeIn(): Fades in the selected element(s).
● .fadeOut(): Fades out the selected element(s).
Event Handling:
jQuery makes it easy to handle events like clicks, mouseovers, and form
submissions.
● .click(function(){ ... }): Executes a function when an element is clicked.
● .mouseover(function(){ ... }): Executes a function when the mouse
pointer enters an element.
● .submit(function(){ ... }): Executes a function when a form is
submitted.
Animation:
jQuery simplifies creating animations.
● .animate({properties}, duration, callback): Animates CSS properties
of an element.
AJAX:
jQuery simplifies making asynchronous requests to the server.
● .ajax({ ... }): Sends an asynchronous HTTP request.

jQuery UI Components for UI Design:

Interactions:
● Draggable: Makes elements draggable.
● Droppable: Allows elements to be dropped onto other elements.
● Resizable: Makes elements resizable.
● Selectable: Allows selecting multiple elements.
● Sortable: Enables items in a list to be sorted.
Widgets:
● Accordion: Displays collapsible content panels.
● Autocomplete: Provides suggestions as the user types.
● Datepicker: Allows users to select dates from a calendar.
● Dialog: Creates modal dialog boxes.
● Tabs: Creates tabbed content areas.
Effects:
● Show/Hide: Controls the visibility of elements with various effects.
● Fade: Fades elements in or out.
● Slide: Slides elements up or down.

Integration with CSS and Responsive Design:

● jQuery can be used to dynamically modify CSS classes and styles, allowing
for dynamic updates to the UI.
● jQuery can be used in conjunction with CSS media queries to create
responsive designs that adapt to different screen sizes.

Benefits of Using jQuery and jQuery UI:

● Ease of Use: jQuery's concise syntax makes it easy to learn and use.
● Cross-Browser Compatibility: jQuery handles many cross-browser issues.
● Rich Set of Features: jQuery and jQuery UI provide a wide range of
features for UI design.
● Extensive Plugin Library: Many plugins extend jQuery's functionality.
● Active Community: A large and active community provides support
and resources.

UI DESIGNING

UI (User Interface) designing focuses on the visual elements and interactivity of a


digital product, like a website or app, to make it user-friendly and visually
appealing. It's about creating a clear, intuitive, and enjoyable experience for the
user. UI designers prioritize aesthetics, usability, and accessibility to ensure the
product is easy to use and engaging.

Key Aspects of UI Designing:

Visual Design:
This involves creating the overall look and feel of the interface, including color
palettes, typography, icons, and other visual elements.
Usability:
Ensuring the interface is easy to navigate and understand, with clear
instructions and intuitive interactions.
Interaction Design:
Focusing on how the user interacts with the interface, including elements like
buttons, menus, and feedback mechanisms.
Accessibility:
Making the interface usable for people with disabilities, considering
factors like screen readers and colorblindness. User-Centered Design:
Designing with the user's needs and goals in mind, prioritizing their
experience.

Tools and Techniques:

Wireframing:
Creating low-fidelity sketches or layouts to plan the structure of the
interface.
Prototyping:
Building interactive mockups to test the usability and functionality of the
interface.
UI Design Software:
Using tools like Figma, Adobe XD, or Sketch to create and design interfaces

In essence, UI design is about creating a digital product that is not only visually
pleasing but also easy to use and engaging for the end-use

You might also like