0% found this document useful (0 votes)
10 views

JavaScript Notes

JavaScript is a lightweight, interpreted programming language widely used for creating dynamic web applications. It is essential for software engineers, especially in web development, due to its popularity, ease of use, and extensive libraries and frameworks. JavaScript supports both client-side and server-side scripting, enabling a variety of applications from web development to mobile app creation.

Uploaded by

isha chatterjee
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

JavaScript Notes

JavaScript is a lightweight, interpreted programming language widely used for creating dynamic web applications. It is essential for software engineers, especially in web development, due to its popularity, ease of use, and extensive libraries and frameworks. JavaScript supports both client-side and server-side scripting, enabling a variety of applications from web development to mobile app creation.

Uploaded by

isha chatterjee
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

JavaScript

Definition
JavaScript is a lightweight, interpreted programming language. It is commonly
used to create dynamic and interactive elements in web applications. JavaScript is
very easy to implement because it is integrated with HTML. It is open and cross-
platform.

Why to Learn JavaScript?


JavaScript is a MUST for students and working professionals to become a great
Software Engineer, especially when they are working in Web Development
Domain. We will list down some of the key advantages of learning JavaScript−

• JavaScript is the most popular programming language in the world,


making it a programmer's great choice. Once you learn JavaScript, it helps
you develop great front-end and back-end software using different
JavaScript based frameworks like jQuery, Node.JS, etc.

• JavaScript is everywhere, it comes installed on every modern web browser


and so to learn JavaScript, you really do not need any special environment
setup. For example, Chrome, Mozilla Firefox, Safari, and every browser you
know as of today, supports JavaScript.

• JavaScript helps you create really beautiful and crazy fast websites. You can
develop your website with a console like look and feel and give your users
the best Graphical User Experience.

• JavaScript usage has now extended to mobile app development, desktop app
development, and game development. This opens many opportunities for
you as JavaScript Programmer.

• Due to high demand, there is tons of job growth and high pay for those who
know JavaScript. You can navigate over to different job sites to see what
having JavaScript skills looks like in the job market.

• Great thing about JavaScript is that you will find tons of frameworks and
Libraries already developed which can be used directly in your software
development to reduce your time to market.

• JavaScript is in all over the world, and companies like Google, Meta,
Microsoft, PayPal, LinkedIn, etc. also use JavaScript.
• Furthermore, JavaScript has more than 1.5 lakh libraries. It is also growing.

• A huge community of JavaScript is available on the internet with students,


developers, and mentors. So anyone can easily get support.

Applications of JavaScript Programming


JavaScript is one of the most widely used programming languages (Front-end as
well as Back-end). It has its presence in almost every area of software
development. I'm going to list few of them here:

• Client side validation − This is really important to verify any user input
before submitting it to the server and JavaScript plays an important role in
validating those inputs at front-end itself.
• Manipulating HTML Pages − JavaScript helps in manipulating HTML
page on the fly. This helps in adding and deleting any HTML tag very easily
using JavaScript and modify your HTML to change its look and feel based
on different devices and requirements.
• User Notifications − You can use JavaScript to raise dynamic pop-ups on
the webpages to give different types of notifications to your website visitors.
• Back-end Data Loading − JavaScript provides Ajax library which helps in
loading back-end data while you are doing some other processing. This
really gives an amazing experience to your website visitors.
• Presentations − JavaScript also provides the facility of creating
presentations which gives website look and feel. JavaScript provides
RevealJS and BespokeJS libraries to build a web-based slide presentation.
• Server Applications − Node JS is built on Chrome's JavaScript runtime for
building fast and scalable network applications. This is an event based
library which helps in developing very sophisticated server applications
including Web Servers.
• Machine learning − Developers can use the ML5.js library to complete the
task related to machine learning.
• Game Developments − JavaScript contains multiple libraries and NPM
packages to design graphics for the game. We can use HTML, CSS, and
JavaScript with libraries to develop the games.
• Mobile applications − We can use frameworks like React Native to build
feature-rich mobile applications.
• Internet of Things (IoT) − JavaScript is used to add functionality to
devices like smartwatches, earbuds, etc.
• Data visualization − JavaScript contains the libraries like D3.js to visualize
the data efficiently. The D3.js is also used to prepare high-quality charts to
visualize the data.
• Cloud computing − We can use JavaScript in serverless computing
platforms like Cloudflare and AWS lambda to write and deploy functions on
the cloud.

This list goes on, there are various areas where millions of software developers are
happily using JavaScript to develop great websites and other software.

Advantages of JavaScript
The merits of using JavaScript are −

• Less server interaction − You can validate user input before sending the
page off to the server. This saves server traffic, which means less load on
your server.
• Immediate feedback to the visitors − They don't have to wait for a page
reload to see if they have forgotten to enter something.
• Increased interactivity − You can create interfaces that react when the user
hovers over them with a mouse or activates them via the keyboard.
• Richer interfaces − You can use JavaScript to include such items as drag-
and-drop components and sliders to give a Rich Interface to your site
visitors.

Limitations of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It lacks the
following important features −

• Client-side JavaScript does not allow the reading or writing of files. This has
been kept for security reasons.
• JavaScript cannot be used for networking applications because no such
support is available.
• JavaScript doesn't have any multi-threading capabilities.
Once again, JavaScript is a lightweight, interpreted programming language
that allows you to build interactivity into otherwise static HTML pages.

Imperative vs. Declarative JavaScript


The imperative and declarative is a programming paradigm, and JavaScript follows
both.

• Imperative JavaScript − In imperative JavaScript, we write code in the


manner that the code describes the steps to get the output. So, we are
concerned about the code execution flow and output both. For example, to
sum all array elements, if we write code for loop, it explains each step to get
the sum.
• Declarative JavaScript − In declarative JavaScript, we don't need to worry
about execution flow, but we should get the correct output at the end. For
example, we use a built-in array.reduce() method to get a sum of array
elements. Here, we don’t concern about how reduce() method is
implemented in the library.

JavaScript Development Tools


One of the major strengths of JavaScript is that it does not require expensive
development tools. You can start with a simple text editor such as Notepad. Since
it is an interpreted language inside the context of a web browser, you don't even
need to buy a compiler.

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

• Visual Studio Code (VS Code) − The VS Code is a code editor used by
most developers to write JavaScript code. It is feature rich and contains
various extensions that can increase the productivity of any developer.
• Chrome dev tools − Programmers may use the Chrome dev tools to debug
the JavaScript code. However, they can use the debugging tool of any
browser as most browser comes with it.

Features of JavaScript
There are following features of JavaScript:
1. All popular web browsers support JavaScript as they provide built-in
execution environments.
2. JavaScript follows the syntax and structure of the C programming
language. Thus, it is a structured programming language.
3. JavaScript is a weakly typed language, where certain types are implicitly
cast (depending on the operation).
4. JavaScript is an object-oriented programming language that uses
prototypes rather than using classes for inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
7. JavaScript is supportable in several operating systems including,
Windows, macOS, etc.
8. It provides good control to the users over the web browsers.

Client-side scripting :

Web browsers execute client-side scripting. It is used when browsers have all
code. Source code is used to transfer from webserver to user’s computer over
the internet and run directly on browsers. It is also used for validations and
functionality for user events.
It allows for more interactivity. It usually performs several actions without
going to the user. It cannot be basically used to connect to databases on a web
server. These scripts cannot access the file system that resides in the web
browser. Pages are altered on basis of the user’s choice. It can also be used to
create “cookies” that store data on the user’s computer.
Client-side scripting simply means running scripts, such as JavaScript, on the
client device, usually within a browser. All kinds of scripts can run on the client
side if they are written in JavaScript, because JavaScript is universally
supported. Other scripting languages can only be used if the user's browser
supports them.
Server-side scripting :

Web servers are used to execute server-side scripting. They are basically used
to create dynamic pages. It can also access the file system residing at the
webserver. A server-side environment that runs on a scripting language is a
web server.
Scripts can be written in any of a number of server-side scripting languages
available. It is used to retrieve and generate content for dynamic pages. It is
used to require to download plugins. In this load times are generally faster
than client-side scripting. When you need to store and retrieve information a
database will be used to contain data. It can use huge resources of the server. It
reduces client-side computation overhead. The server sends pages to the
request of the user/client.

Difference between client-side scripting and server-side scripting


:
Client-side scripting Server-side scripting
Client-side scripting Server-side scripting

Source code is not visible to the user because its


output
Source code is visible to the user.
of server-sideside is an HTML page.

Its primary function is to manipulate and


Its main function is to provide the
provide access to the respective database as per
requested output to the end user.
the request.

In this any server-side technology can be used


It usually depends on the browser and it does not
and its version. depend on the client.

It runs on the user’s computer. It runs on the webserver.

There are many advantages linked


The primary advantage is its ability to highly
with this like faster.
customize, response
response times, a more interactive
requirements, access rights based on user.
application.

It does not provide security for data. It provides more security for data.

It is a technique used in web It is a technique that uses scripts on the


development in which scripts run on webserver to produce a response that is
the client’s browser. customized for each client’s request.

HTML, CSS, and javascript are used. PHP, Python, Java, Ruby are used.

No need of interaction with the


It is all about interacting with the servers.
server.

It reduces load on processing unit of


It surge the processing load on the server.
the server.

JavaScript Variables
JavaScript variables are used to store data that can be changed later on. The
ariables can be thought of as named containers. You can place data into these
containers and then refer to the data simply by naming the container.

Before you use a variable in a JavaScript program, you must declare it. In
JavaScript, you can declare the variables in 4 ways −

• Without using any keywords.


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

JavaScript Variables
Variable means anything that can vary. In JavaScript, a variable stores
data that can be changed later on.

Declare a Variable
In JavaScript, a variable can be declared using var, let, const keywords.
• var keyword is used to declare variables since JavaScript was created. It is
confusing and error-prone when using variables declared using var.
• let keyword removes the confusion and error of var. It is the new and
recommended way of declaring variables in JavaScript.
• const keyword is used to declare a constant variable that cannot be changed
once assigned a value.

Here, we will use the let keyword to declare variables. To declare a


variable, write the keyword let followed by the name of the variable you
want to give, as shown below.

Example: Variable Declaration


let msg; // declaring a variable without assigning a value

In the above example, var msg; is a variable declaration. It does not have
any value yet. The default value of variables that do not have any value
is undefined.

You can assign a value to a variable using the = operator when you
declare it or after the declaration and before accessing it.
Example: Variable Initialization
let msg;
msg = "Hello JavaScript!"; // assigning a string value

In the above example, the msg variable is declared first and then assigned
a string value in the next line.

You can declare a variable and assign a value to it in the same line.
Values can be of any datatype such as string, numeric, boolean, etc.

Example: Variable Declaration and Initialization


let name = "Steve"; //assigned string value
let num = 100; //assigned numeric value
let isActive = true; //assigned boolean value

Multiple variables can be declared in a single line, as shown below.

Example: Multiple Variables


let name = "Steve", num = 100, isActive = true;

You can copy the value of one variable to another variable, as shown
below.

Example: Copy Variable


let num1 = 100;
let num2 = num1;

JavaScript allows multiple white spaces and line breaks when you
declare a variables.

Example: Whitespace and Line Breaks


let name = "Steve",
num = 100,
isActive = true;

Variable names are case-sensitive in JavaScript. You cannot declare a


duplicate variable using the let keyword with the same name and case.
JavaScript will throw a syntax error. Although, variables can have the
same name if declared with the var keyword (this is why it is
recommended to use let).

Example: Syntax Error


let num = 100;
let num = 200; //syntax error

var num = 100;


var num = 200; //Ok

JavaScript Variable Nameing Conventions


• Variable names are case-sensitive in JavaScript. So, the variable
names msg, MSG, Msg, mSg are considered separate variables.
• Variable names can contain letters, digits, or the symbols $ and _.
• A variable name cannot start with a digit 0-9.
• A variable name cannot be a reserved keyword in JavaScript, e.g. var,
function, return cannot be variable names.

Dynamic Typing
JavaScript is a loosely typed language. It means that you don't need to
specify what data type a variable will contain. You can update the value
of any type after initialization. It is also called dynamic typing.

Example: Loosely Typed Variable


let myvariable = 1; // numeric value

myvariable = 'one'; // string value

myvariable = 1.1; // decimal value

myvariable = true; // Boolean value

myvariable = null; // null value

Constant Variables in JavaScript


Use const keyword to declare a constant variable in JavaScript.
• Constant variables must be declared and initialized at the same time.
• The value of the constant variables can't be changed after initialized them.
Example: Constant Variables
const num = 100;
num = 200; //error

const name; //error


name = "Steve";

The value of a constant variable cannot be changed but the content of the
value can be changed. For example, if an object is assigned to a const
variable then the underlying value of an object can be changed.

Example: Constant Variables


const person = { name: 'Steve'};
person.name = "Bill";
alert(person.name); //Bill

It is best practice to give constant variable names in capital letters to


separate them from other non-constant variables.

Variable Scope
In JavaScript, a variable can be declared either in the global scope or the
local scope.

Global Variables
Variables declared out of any function are called global variables. They
can be accessed anywhere in the JavaScript code, even inside any
function.

Local Variables
Variables declared inside the function are called local variables of that
function. They can only be accessed in the function where they are
declared but not outside.

The following example includes global and local variables.

Example: Global and Local Variable


let greet = "Hello " // global variable
function myfunction(){
let msg = "JavaScript!";
alert(greet + msg); //can access global and local variable
}

myfunction();

alert(greet);//can access global variable


alert(msg); //error: can't access local variable

Declare Variables without var and let Keywords


Variables can be declared and initialized without the var or let keywords.
However, a value must be assigned to a variable declared without
the var keyword.

The variables declared without the var keyword become global variables,
irrespective of where they are declared. It is recommended to declare
variable using the let keyword.

Example: Variable Declaration Without var or let Keyword


function myfunction(){
msg = "Hello JavaScript!";
}

myfunction();
alert(msg); // msg becomes global variable so can be accessed here

What is an Operator?
In JavaScript, an operator is a symbol that performs an operation on one or more
operands, such as variables or values, and returns a result. Let us take a simple
expression 4 + 5 is equal to 9. Here 4 and 5 are called operands, and ‘+’ is called
the operator.

JavaScript supports the following types of operators.

• Arithmetic Operators
• Comparison Operators
• Logical (or Relational) Operators
• Bitwise Operators
• Assignment Operators
• Miscellaneous Operators
Lets have a look on all operators one by one.

JavaScript Arithmetic Operators


The JavaScript arithmetic operators are used to perform mathematical calculations
such as addition, multiplication, subtraction, division, etc. on numbers. JavaScript
supports the following arithmetic operators −

Assume variable x holds 10 and variable y holds 20, then −

Operator Description Example

+ (Addition) Adds two operands. x + y will give 30.

Subtracts the second operand


- (Subtraction) x - y will give -10.
from the first.

* (Multiplication) Multiplies both operands. x * y will give 200.


Divides the numerator by the
/ (Division) y / x will give 2.
denominator.

Divides the numerator by the


/ (Division) y / x will give 2.
denominator.

Outputs the remainder of an


% (Modulus) y % x will give 0
integer division.
Increases an integer value by
++ (Increment) x++ will give 11.
one.

Decreases an integer value by


-- (Decrement) x-- will give 9.
one.
Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will
give "a10".

JavaScript Comparison Operators


The JavaScript comparison operators compare two values and returns a boolean
result (true or false). JavaScript supports the following comparison operators −

Assume variable x holds 10 and variable y holds 20, then –


Operator Description Example

Checks if the value of two operands is


== (Equal) equal or not. If yes, then the condition (x == y) is not true.
becomes true.

Checks if the value of two operands is


!= (Not Equal) equal or not. If the values are not equal, (x != y) is true.
then the condition becomes true.

It checks whether the value and data type


=== (Strict equality) of the variable is equal or not. If yes, then (x === y) is not true.
the condition becomes true.

It checks whether the value and data type


of the variable is equal or not. If the
!== (Strict inequality) (x !== y) is true.
values are not equal, then the condition
becomes true.

Checks if the value of the left operand is


> (Greater than) greater than the value of the right operand. (x > y) is not true.
If yes, then the condition becomes true.

Checks if the value of the left operand is


< (Less than) less than the value of the right operand. If (x < y) is true.
yes, then the condition becomes true.

Checks if the value of the left operand is


greater than or equal to the value of the
>= (Greater than or Equal to) (x >= y) is not true.
right operand. If yes, then the condition
becomes true.

Checks if the value of the left operand is


less than or equal to the value of the right
<= (Less than or Equal to) (x <= y) is true.
operand. If yes, then the condition
becomes true.

JavaScript Logical Operators


The logical operators are generally used to perform logical operations on boolean
values. But logical operators can be applied to values of any types not only
boolean.

JavaScript supports the following logical operators −

Assume that the value of x is 10 and y is 0.


Operator Description Example
If both the operands are non-zero, then the
&& (Logical AND) (x && y) is false
condition becomes true.
If any of the two operands are non-zero,
|| (Logical OR) (x || y) is true.
then the condition becomes true.

Reverses the logical state of its operand. If


! (Logical NOT) a condition is true, then the Logical NOT !x is false.
operator will make it false.

JavaScript Bitwise Operators


The JavaScript bitwise operators are used to perform bit-level operations on
integers. JavaScript supports the following seven types of bitwise operators −

Assume variable x holds 2 and variable y holds 3, then −

Operator Description Example

It performs a Boolean AND operation on


& (Bitwise AND) (x & y) is 2.
each bit of its integer arguments.

It performs a Boolean OR operation on each


| (Bitwise OR) (x | y) is 3.
bit of its integer arguments.

It performs a Boolean exclusive OR


operation on each bit of its integer
^ (Bitwise XOR) arguments. Exclusive OR means that either (x ^ y) is 1.
operand one is true or operand two is true,
but not both.

It is a unary operator and operates by


~ (Bitwise Not) (~y) is -4.
reversing all the bits in the operand.

It moves all the bits in its first operand to the


left by the number of places specified in the
second operand. New bits are filled with
<< (Left Shift) zeros. Shifting a value left by one position is (x << 1) is 4.
equivalent to multiplying it by 2, shifting
two positions is equivalent to multiplying by
4, and so on.

Binary Right Shift Operator. The left


>> (Right Shift) operand’s value is moved right by the (x >> 1) is 1.
number of bits specified by the right
operand.

This operator is just like the >> operator,


>>> (Right shift with Zero) except that the bits shifted in on the left are (x >>> 1) is 1.
always zero.

JavaScript Assignment Operators


In JavaScript, an assignment operator is used to assign a value to a variable.
JavaScript supports the following assignment operators −

Operator Description Example

z=x+y
will
= (Simple
Assigns values from the right side operand to the left side operand assign the
Assignment)
value of x
+ y into z

z += x is
+= (Add
It adds the right operand to the left operand and assigns the result to the equivalent
and
left operand. to z = z +
Assignment)
x

z -= x is
−= (Subtract
It subtracts the right operand from the left operand and assigns the equivalent
and
result to the left operand. to z = z -
Assignment)
x

z *= x is
*=(Multiply
It multiplies the right operand with the left operand and assigns the equivalent
and
result to the left operand. to z = z *
Assignment)
x

z /= x is
/= (Divide
It divides the left operand with the right operand and assigns the result equivalent
and
to the left operand. to z = z /
Assignment)
x

%= z %= x is
(Modules It takes modulus using two operands and assigns the result to the left equivalent
and operand. to z = z %
Assignment) x
Same logic applies to Bitwise operators so they will become like <<=, >>=, >>=,
&=, |= and ^=.
JavaScript Miscellaneous Operators
There are few other operators supported by JavaScript. These operators
are conditional operator (? :), typeof operator, delete operator, etc.

In the below table, we have given the JavaScript miscellaneous operators with its
explanation.

Operator Description

If Condition is true? Then value X : Otherwise


? : (Conditional )
value Y

typeof It returns the data type of the operand.

It returns its right-hand side operand when its left-


?? (Nullish Coalescing Operator) hand side operand is null or undefined, and
otherwise returns its left-hand side operand.
delete It removes a property from an object.

It evaluates its operands (from left to right) and


, (Comma)
returns the value of the last operand.

() (Grouping) It allows to change the operator precedence.

It is used to pause and resume a generator


yield
function.

It is used to expand the iterables such as array or


… (Spread)
string.

Raises the left operand to the power of the right


** (Exponentiation)
operand

JavaScript Arithmetic Operators


Arithmetic operators in JavaScript perform mathematical calculations on numeric
values (operands). Most of the arithmetic operators are binary operators as they
perform calculations on two operands. Some arithmetic operators are unary
operators. The unary operators perform computation on a single operand.

JavaScript supports many arithmetic operators such as addition, subtraction,


multiplication, division operators, etc. It uses the common symbols for arithmetic
operators such as "+" for addition, "-" for subtraction, "*" for multiplication, "/ "
for division etc.

The operands can be literals, variables or the expression.

n general, arithmetic operators are used to perform mathematical operations but


they can be used for other operations as well. For example, the addition operator
(+) can be used for string concatenation.

Here, we have given a table containing the mathematical operators and explaining
the functionality of each operator.

Operator Name Description


+ Addition Adds two operands

- Subtraction Subtracts the second operand from the first


* Multiplication Multiply both operands

/ Division Divide the numerator by the denominator


% Modulus Outputs the remainder of an integer division

++ Increment Increases an integer value by one


-- Decrement Decreases an integer value by one

Let's discuss the different operators with the help of examples.

JavaScript Addition (+) Operator


The JavaScript addition (+) operator adds two numeric operands. It is denoted by
the plus (+) symbol. This operator can also be used to concatenate strings and/or
numbers.

• If one operand is string, the addition operator converts the other operand to
string and concatenate it with first operand.
• If both the operands are string, it just concatenates the second operand to the
first operand.
• If both operands are numeric values, it will return the numeric value.

JavaScript Subtraction (-) Operator


JavaScript subtraction (-) operator subtracts the right operand from the left operand
and produces their difference. It is denoted by the minus (-) symbol.

• The subtraction operator uses numeric operands but can also be used for
non-numeric operands such as strings.
• If both operands are numbers, then resultant is number.
• If any or both operands are strings (containing only numbers), it first
converts the strings to number and then performs subtraction operations.
• If string contains non numeric value, it will return NaN.
• If any operand is NaN or Infinity, the result will be NaN or Infinity
respectively.

JavaScript Multiplication (*) Operator


The JavaScript multiplication operator multiplies two numbers (operands). It gives
the product of two operands. It is denoted by the asterisk (*) symbol. If two
operands are of same sign, the product is positive. If the two operands are of
different sign, the product is negative.

If any or both operands are string, it converts the string to number and then returns
their product.

JavaScript Division (/) Operator


The JavaScript division (/) operator divides the left operand (dividend) by the right
operand (divisor) and returns the quotient. It is represented by the slash (/) symbol.

JavaScript Modulus (%) Operator


The JavaScript modulus (%) operator returns the remainder when first operand is
divided by the second operand. It is also known as remainder operator. It is
denoted by the percent (%) symbol. It takes the sign of dividend. Let’s take an
example 5%3 gives 2 because when 5 is divided by 3, it gives remainder as 2.

JavaScript Increment (++) Operator


The JavaScript increment (++) operator increases the value of operand by one. It is
an unary operator. It takes only one operand. It is denoted by double plus (++)
sign.

There are two types of increment operator in JavaScript −


Prefix Increment Operator

The prefix increment operator increments the value of the variable before its
current value is used.

Postfix Increment Operator

The postfix increment operator increments the value of the variable after its current
value is used.

JavaScript Decrement (--) Operator


The JavaScript decrement (--) operator decreases the value of operand by one. It is
also an unary operator, i.e., it takes only one operand. It is denoted by double
minus (--) sign.

There are two types of decrement operator in JavaScript −

Prefix Decrement Operator

The prefix decrement operator decrements the value of the variable before its
current value is used.

Postfix Decrement Operator

The postfix decrement operator decrements the value of the variable after its
current value is used.

Conditional Statements in JavaScript


JavaScript Conditional statements allow you to execute specific blocks of
code based on conditions. If the condition meets then a particular block of
action will be executed otherwise it will execute another block of action that
satisfies that particular condition.
There are several methods that can be used to perform Conditional Statements
in JavaScript.
• if statement: Executes a block of code if a specified condition is true.
• else statement: Executes a block of code if the same condition of the
preceding if statement is false.
• else if statement: Adds more conditions to the if statement, allowing for
multiple alternative conditions to be tested.
• switch statement: Evaluates an expression, then executes the case
statement that matches the expression’s value.
• ternary operator (conditional operator): Provides a concise way to write
if-else statements in a single line.
• Nested if else statement: Allow for multiple conditions to be checked in a
hierarchical manner.

JavaScript Conditional statements Examples:


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

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

Example: In this example, we are using the if statement to find given


number is even or odd.
let num = 20;

if (num % 2 === 0) {
console.log("Given number is even number.");
}

if (num % 2 !== 0) {
console.log("Given number is odd number.");
};

2. Using if-else Statement


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

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

Example: In this example, we are using if-else conditional statement to check


the driving licence eligibility date.
let age = 25;

if (age >= 18) {


console.log("You are eligible of driving licence")
} else {
console.log("You are not eligible for driving licence")
};
3. else if Statement
The else if statement in JavaScript allows handling multiple possible
conditions and outputs, evaluating more than two options based on whether the
conditions are true or false.

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

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


const num = 0;

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

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

Syntax:
switch (expression) {
case value1:
statement1;
break;
case value2:
statement2;
break;
. . .
case valueN:
statementN;
break;
default:
statementDefault;
};

Example: In this example, we find a branch name Based on the student’s


marks, this switch statement assigns a specific engineering branch to the
variable Branch. The output displays the student’s branch name

const marks = 85;

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}`);

5. Using Ternary Operator ( ?: )


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

Syntax:
condition ? value if true : value if false
Example: In this example, we use the ternary operator to check if the user’s
age is 18 or older. It prints eligibility for voting based on the condition.
let age = 21;

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

console.log(result);

JavaScript Pop-Up Boxes


In Javascript, popup boxes are used to display the message or notification to
the user.
There are three types of pop-up boxes in JavaScript:

• Alert Box
• Prompt Box
• Confirm Box

Alert Box
It is used when a warning message is needed to be produced. When the alert
box is displayed to the user, the user needs to press ok and proceed.

Syntax:
alert("your Alert here");

Example: This example shows the implementation of the alert box.


<!DOCTYPE html>
<html>
<head>
<title>Pop-up Box type | Alert Box</title>
<style>
h1{
color:green;
}
</style>
</head>

<body>
<center>
<h1>GeeksforGeeks</h1>
<h3>Alert Box</h3>
<button onclick="geekAlert()">
Click here for alert box
</button>

<!-- Alert box function -->


<script>
function geekAlert() {
alert("An Online Computer Science"
+ "Portal for Geeks");
}
</script>
</center>
</body>
</html>

Prompt Box
It is a type of pop up box which is used to get the user input for further use.
After entering the required details user have to click ok to proceed next stage
else by pressing the cancel button user returns the null value.

Syntax:
prompt("your Prompt here");

Example: This example shows the implementation of the Prompt box.


<!DOCTYPE html>
<html>
<head>
<title>
Pop-up Box type | Prompt Box
</title>
<style>
h1 {
color: green;
}
</style>
</head>

<body>
<center>
<h1>GeeksforGeeks</h1>

<h3>Prompt Box</h3>

<input type="button" onclick="geekPrompt();"


value="Click here for Prompt box"/>

<!-- Prompt box function -->


<script>
function geekPrompt() {
let x = prompt("Enter your mail here : ");
document.write("Your ID : " + x);
}
</script>
</center>
</body>
</html>
Confirm Box
It is a type of pop-up box that is used to get authorization or permission from
the user. The user has to press the ok or cancel button to proceed.

Syntax:
confirm("your query here");

Example: This example shows the implementation of the Confirm box.


<!DOCTYPE html>
<html>

<head>
<title>
Pop-up Box type | Confirm Box
</title>
<style>
h1 {
color: green;
}
</style>
</head>

<body>
<center>

<h1>GeeksforGeeks</h1>

<h3>Confirm Box</h3>

<button onclick="geekConfirm()">
Click here for Confirm box
</button>

<p id="geek"></p>

<!-- Confirm box function -->


<script>
function geekConfirm() {
var x;
if (confirm("Press a button!") == true) {
x = "OK pressed!";
} else {
x = "Cancel!";
}
document.getElementById("geek").innerHTML = x;
}
</script>
</center>
</body>

</html>

JavaScript Events
JavaScript Events are actions or occurrences that happen in the browser.
They can be triggered by various user interactions or by the browser itself.
Common events include mouse clicks, keyboard presses, page loads, and form
submissions. Event handlers are JavaScript functions that respond to these
events, allowing developers to create interactive web applications.

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

Common JavaScript Events


• onclick: Triggered when an element is clicked.
• onmouseover: Fired when the mouse pointer moves over an element.
• onmouseout: Occurs when the mouse pointer leaves an element.
• onkeydown: Fired when a key is pressed down.
• onkeyup: Fired when a key is released.
• onchange: Triggered when the value of an input element changes.
• onload: Occurs when a page has finished loading.
• onsubmit: Fired when a form is submitted.
• onfocus: Occurs when an element gets focus.
• onblur: Fired when an element loses focus.

JavaScript Events Examples


Example 1: Here, we will display a message in the alert box when the button
is clicked using onClick() event. This HTML document features a button
styled to appear in the middle of the page. When clicked, the button triggers
the `hiThere()` JavaScript function, which displays an alert box with the
message “Hi there!”.

<!doctype html>
<html>

<head>
<script>
function hiThere() {
alert('Hi there!');
}
</script>
</head>
<body>
<button type="button"
onclick="hiThere()"
style="margin-left: 50%;">
Click me event
</button>
</body>

</html>

Example 2: Here, we will change the color by pressing UP arrow key using
onkeyup() event. This code defines a JavaScript function
`changeBackground()` that changes the background color of an input box
when the up arrow key is pressed. RGB color values are incremented with
each key press, cycling through colors.

<!doctype html>
<html>

<head>
<script>
let a=0;
let b=0;
let c=0;
function changeBackground() {
let x=document.getElementById('bg');
x.style.backgroundColor='rgb('+a+', '+b+', '+c+')';
a+=100;
b+=a+50;
c+=b+70;
if(a>255) a=a-b;
if(b>255) b=a;
if(c>255) c=b;
}
</script>
</head>

<body>
<h4>The input box will change color when UP arrow key is
pressed</h4>
<input id="bg" onkeyup="changeBackground()" placeholder="write
something" style="color:#fff">
</body>

</html>

JavaScript Event Handlers


JavaScript event handlers are functions that are executed in response to
specific events occurring in the browser.
They can be attached to HTML elements using event attributes
like onclick, onmouseover, etc., or added dynamically using
the addEventListener() method in JavaScript.
Example: Here’s an example of a JavaScript event handler attached to an
HTML button element using the onclick attribute. This code demonstrates an
event handler attached to a button element. When the button is clicked, the
`myFunction()` JavaScript function is invoked, triggering an alert box
displaying “Button clicked!”.
<!DOCTYPE html>
<html>
<head>
<title>Event Handler Example</title>
</head>
<body>

<button onclick="myFunction()">Click me</button>

<script>
// JavaScript function to handle the click event
function myFunction() {
alert("Button clicked!");
}
</script>

</body>
</html>

JavaScript Custom Events


Events are used in almost every web application, such as the onclick event is
used to execute some code when the user clicks on something. There are
already numerous built-in events available to be used, but what if we want our
custom event? Let us suppose we are creating a chat application, and we want
to execute some code when the end-user sends some message. There is no
built-in event to detect that. Here we need a custom event that can handle such
custom scenarios.

Creating a Custom Event:


To create a custom event we use the Event constructor
or CustomEvent interface. The Event constructor creates an Event and
CustomEvent creates an Event with more functionality.
The below steps are followed to create one using a new Event.
• We create an event using the Event constructor.
• We listen to this event using the addEventListener() method.
• We trigger or dispatch the event
using element.dispatchEvent(eventName) method.
• A custom Event named start has now been created.

Syntax:
// To assign event
const startEvent = new Event("start");
// To trigger the event Listener
document.addEventListener("start", () => {
console.log("The start event was triggered")
});
// To trigger the Event
document.dispatchEvent(startEvent);

Example: We are creating an event that is triggered when the value of x is 5.


<html>
<body>
<script>
let x = 5;
const event = new Event("start");

document.addEventListener('start', ()=>{
console.log("Start event triggered")
});

if(x == 5){
document.dispatchEvent(event);
}
</script>
</body>
</html>

Creating a custom event using CustomEvent:

Creating custom events using the CustomEvent interface has an advantage as


it can send custom data. The below steps are followed in order to create a new
CustomEvent.
• We create a custom event using the CustomEvent constructor.
• This takes two arguments, the first is the name of the event and the second
is an object that contains the data. The property name inside the object
name should be named detail otherwise it won’t work.
• We create a listener for this event.
• We trigger or dispatch the event.
• A custom event that contains data has been created.

Syntax:
// To assign event
const event = new CustomEvent("start", {
detail: {
platform : "GeeksforGeeks"
}
});
// To trigger the event Listener
document.addEventListener('start', (e)=>{
console.log(
`start event triggered on platform :
${e.detail.platform}`
);
});
// To trigger the Event
document.dispatchEvent(event);

Example: In this example, we are creating a custom event that triggers when
the value of x is 5.
<html>
<body>
<script>
let x = 5;
const event = new CustomEvent("start", {
detail: {
platform : "GeeksforGeeks"
}
});

document.addEventListener('start', (e) => {


console.log(
`Start event triggered on platform
${e.detail.platform}`
);
})

if (x == 5) {
document.dispatchEvent(event);
}
</script>
</body>
</html>

Note: We are dispatching the event directly from the document


using document.dispatchEvent(‘start’), but one can dispatch the event from
any needed element like myBtn.dispatchEvent(‘start’).
JavaScript - Form Validation
Form validation normally used to occur at the server, after the client had entered all
the necessary data and then pressed the Submit button. If the data entered by a
client was incorrect or was simply missing, the server would have to send all the
data back to the client and request that the form be resubmitted with correct
information. This was really a lengthy process which used to put a lot of burden on
the server.

JavaScript provides a way to validate form's data on the client's computer before
sending it to the web server. Form validation generally performs two functions.

• Basic Validation − First of all, the form must be checked to make sure all
the mandatory fields are filled in. It would require just a loop through each
field in the form and check for data.
• Data Format Validation − Secondly, the data that is entered must be
checked for correct form and value. Your code must include appropriate
logic to test correctness of data.

JavaScript Form Validation ensures data integrity by verifying user input


before submission. It validates fields like passwords, emails, and selections,
providing alerts for invalid data, and enhancing user experience and data
accuracy.
Approach for Form Validation in JavaScript
In this approach, we are following these steps
• Data Retrieval: It retrieves the values of various form fields like name,
email, course selection, password, and address using
document.forms.RegForm.
• Data Validation:
• Name Validation: Checks if the name field is empty or contains
any digits.
• Address Validation: Ensures the address field is not empty.
• Email Validation: Verifies if the email field is not empty and
contains the ‘@’ symbol.
• Password Validation: Validates that the password field is not
empty and has a minimum length of 6 characters.
• Course Selection Validation: Ensures that a course is selected
from the dropdown.
• Error Handling:
• If any of the validation criteria fail, it displays an alert message
using window.alert.
• Sets focus back to the respective field that failed validation,
ensuring the user’s attention is drawn to the problematic field.
• Submission Control:


Returns true if all validation checks pass, indicating that the form
can be submitted. Otherwise, it returns false, preventing form
submission.
• Focus Adjustment:
• Sets focus to the first field that failed validation, ensuring the
user’s attention is drawn to the problematic field.
Example: Here, we are following above explained apporach.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0"
/>
<title>Form Validation</title>
<link rel="stylesheet" href="style.css" />
</head>

<body>
<h1>REGISTRATION FORM</h1>
<form
name="RegForm"
onsubmit="return validateForm()"
>
<p>
<label for="name">Name:</label>
<input
type="text"
id="name"
name="Name"
placeholder="Enter your full name"
/>
<span
id="name-error"
class="error-message"
></span>
</p>
<p>
<label for="address"
>Address:</label
>
<input
type="text"
id="address"
name="Address"
placeholder="Enter your address"
/>
<span
id="address-error"
class="error-message"
></span>
</p>
<p>
<label for="email"
>E-mail Address:</label
>
<input
type="text"
id="email"
name="EMail"
placeholder="Enter your email"
/>
<span
id="email-error"
class="error-message"
></span>
</p>
<p>
<label for="password"
>Password:</label
>
<input
type="password"
id="password"
name="Password"
/>
<span
id="password-error"
class="error-message"
></span>
</p>
<p>
<label for="subject"
>Select Your Course: </label
>
<select
id="subject"
name="Subject"
>
<option value="">
Select Course
</option>
<option value="BTECH">
BTECH
</option>
<option value="BBA">
BBA
</option>
<option value="BCA">
BCA
</option>
<option value="B.COM">
B.COM
</option>
</select>
<span
id="subject-error"
class="error-message"
></span>
</p>
<p>
<label for="comment"
>College Name:</label
>
<textarea
id="comment"
name="Comment"
></textarea>
</p>
<p>
<input
type="checkbox"
id="agree"
name="Agree"
/>
<label for="agree"
>I agree to the above
information</label
>
<span
id="agree-error"
class="error-message"
></span>
</p>
<p>
<input
type="submit"
value="Send"
name="Submit"
/>
<input
type="reset"
value="Reset"
name="Reset"
/>
</p>
</form>
<script src="script.js"></script>
</body>
</html>

Types of Form Validation


• Client-side validation: JavaScript is typically used to validate forms on the
user’s browser before submission. This provides immediate feedback to
users and prevents unnecessary server requests.
• Server-side validation: Even with client-side validation, it’s crucial to re-
validate form data on the server-side. This reduce any potential issues that
might arise due to disabled JavaScript or browser manipulation.

AngularJS - Overview
AngularJS is a structural framework for dynamic web applications. It lets you use
HTML as your template language and lets you extend HTML's syntax to express
your application components clearly and succinctly. Its data binding and
dependency injection eliminate much of the code you currently have to write. And
it all happens within the browser, making it an ideal partner with any server
technology.

AngularJS is an open-source web application framework. It was originally


developed in 2009 by Misko Hevery and Adam Abrons. It is now maintained by
Google. Its latest version is 1.2.21.

General Features
The general features of AngularJS are as follows −

• AngularJS is a efficient framework that can create Rich Internet


Applications (RIA).
• AngularJS provides developers an options to write client side applications
using JavaScript in a clean Model View Controller (MVC) way.
• Applications written in AngularJS are cross-browser compliant. AngularJS
automatically handles JavaScript code suitable for each browser.
• AngularJS is open source, completely free, and used by thousands of
developers around the world. It is licensed under the Apache license version
2.0.

Overall, AngularJS is a framework to build large scale, high-performance, and


easyto-maintain web applications.
Core Features
The core features of AngularJS are as follows −

• Data-binding − It is the automatic synchronization of data between model


and view components.
• Scope − These are objects that refer to the model. They act as a glue
between controller and view.
• Controller − These are JavaScript functions bound to a particular scope.
• Services − AngularJS comes with several built-in services such as $http to
make a XMLHttpRequests. These are singleton objects which are
instantiated only once in app.
• Filters − These select a subset of items from an array and returns a new
array.
• Directives − Directives are markers on DOM elements such as elements,
attributes, css, and more. These can be used to create custom HTML tags
that serve as new, custom widgets. AngularJS has built-in directives such as
ngBind, ngModel, etc.
• Templates − These are the rendered view with information from the
controller and model. These can be a single file (such as index.html) or
multiple views in one page using partials.
• Routing − It is concept of switching views.
• Model View Whatever − MVW is a design pattern for dividing an
application into different parts called Model, View, and Controller, each
with distinct responsibilities. AngularJS does not implement MVC in the
traditional sense, but rather something closer to MVVM (Model-View-
ViewModel). The Angular JS team refers it humorously as Model View
Whatever.
• Deep Linking − Deep linking allows to encode the state of application in
the URL so that it can be bookmarked. The application can then be restored
from the URL to the same state.
• Dependency Injection − AngularJS has a built-in dependency injection
subsystem that helps the developer to create, understand, and test the
applications easily.

Advantages of AngularJS
The advantages of AngularJS are −

• It provides the capability to create Single Page Application in a very clean


and maintainable way.
• It provides data binding capability to HTML. Thus, it gives user a rich and
responsive experience.
• AngularJS code is unit testable.
• AngularJS uses dependency injection and make use of separation of
concerns.
• AngularJS provides reusable components.
• With AngularJS, the developers can achieve more functionality with short
code.
• In AngularJS, views are pure html pages, and controllers written in
JavaScript do the business processing.

On the top of everything, AngularJS applications can run on all major browsers
and smart phones, including Android and iOS based phones/tablets.

Disadvantages of AngularJS
Though AngularJS comes with a lot of merits, here are some points of concern −

• Not Secure − Being JavaScript only framework, application written in


AngularJS are not safe. Server side authentication and authorization is must
to keep an application secure.
• Not degradable − If the user of your application disables JavaScript, then
nothing would be visible, except the basic page.

AngularJS Directives
The AngularJS framework can be divided into three major parts −

• ng-app − This directive defines and links an AngularJS application to


HTML.
• ng-model − This directive binds the values of AngularJS application data to
HTML input controls.
• ng-bind − This directive binds the AngularJS application data to HTML
tags.

AngularJS Expressions
In this article, we will see the Expressions in AngularJS, along with
understanding their implementation through the examples.
Expressions in AngularJS are used to bind application data to HTML. The
expressions are resolved by AngularJS and the result is returned back to where
the expression is written. The expressions in AngularJS are written in double
braces: {{ expression }}. They behave similar to ng-bind directives: ng-
bind=”expression”.
Syntax:
{{ expression }}

AngularJS Modules
The AngularJS module defines the functionality of the application which is
applied on the entire HTML page. It helps to link many components. So it is
just a group of related components. It is a container that consists of different
parts like controllers, services, and directives.
Note: These modules should be made in normal HTML files like index.html
and no need to create a new project in VisualStudio for this section.

Creating a Module in AngularJS:


var app = angular.module("Module-name", []);
In this [], we can add a list of components needed but we are not including any
components in this case. This created module is bound with any tag like div,
body, etc by adding it to the list of modules.
<div ng-app = "module-name">
The code in which the module is required.
</div>
Adding a Controller:
app.controller("Controller-name", function($scope) {
$scope.variable-name= "";
});
Here, we can add any number of variables in the controller and use them in the
HTML files, and the body of the tag in which the controller is added to that tag
by writing:
<body>
<div ng-app="Module-name">
<div ng-controller="Controller-name">
{{variable-name}}
</div>

<!-- This wont get printed since its


not part of the div in which
controller is included -->
{{variable-name}}
</div>
</body>
Module and Controllers in Files: While we can make modules and
controllers in the same file along with the HTML file which requires it
however we may want to use this module in some other file. Hence this will
lead to redundancy so we will prefer to create Module, Controller, and HTML
files separately. The Module and Controller are to be stored by using .js files.

AngularJS Directive
AngularJS is a Javascript open-source front-end framework that is mainly used
to develop single-page web applications(SPAs). It has the ability to change
static HTML to dynamic HTML. Its features like dynamic binding and
dependency injection eliminate the need for code that we have to write
otherwise.
Directives are markers on the DOM element which tell AngularJS to attach a
specified behavior to that DOM element or even transform the DOM element
with its children. Simple AngularJS allows extending HTML with new
attributes called Directives. AngularJS has a set of built-in directives which
offers functionality to the applications. It also defines its own directives. A
directive can be defined using some functions which are: Element name,
Attribute, Class, and Comment.

Why use Directive in AngularJS?


• It gives support to creating custom directives for different types of elements.
• A directive is activated when the same element or matching element is there
in front.
• It is used to give more power to HTML by helping them with the new
syntax.
• Directive classes, like component classes, can implement life-cycle hooks to
influence their configuration and behavior.

Directive Components: The AngularJS directives extend the attribute with


the prefix ng-. Some directive components are discussed below:

1. ng-app: The ng-app directive is used to define the root element of an


AngularJS application. This directive automatically initializes the AngularJS
application on page load.

2. ng-controller: The ng-controller Directive in AngularJS is used to add the


controller to the application. It can be used to add methods, functions, and
variables that can be called on some event like a click, etc to perform a certain
action.
3. ng-bind: The ng-bind directive is used to bind/replace the text content of a
particular element with the value that is entered in the given expression. The
value of specified HTML content updates whenever the value of the
expression changes in the ng-bind directive.
Benefits of AngularJS Directive:
• Directives are helpful in creating repeat and independent code.
• They modularize the code by clubbing requirement-specific behavioral
functions in one place. It does not create objects in the central controller
and manipulate them using multiple JavaScript methods.
• Such a type of modular code will have multiple directives that can handle
their own functionalities and data, and work should be isolated from other
directives.
• As an added benefit, the HTML page and Angular scripts become less
messy and more organized.

You might also like