Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
196 views

Java Script Part1 PPT-Unit2 MSD

Uploaded by

P.Padmini Rani
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
196 views

Java Script Part1 PPT-Unit2 MSD

Uploaded by

P.Padmini Rani
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 135

Java Script

Why we need JavaScript?


When an application is loaded on
the browser, there is a 'SignUp'
link on the top right corner.
When this link is clicked, the
'SignUp' form is displayed. It
contains three fields - 'Username',
'Email', and 'Password' and in
some cases a 'Submit' button as
well.
When data is entered in the fields
and the button is clicked, then data
entered in the fields will be
validated and accordingly, next
view page loaded. If data is invalid,
an error message is displayed, if
valid, the application navigates to
homepage.
How to handle the user click,
validate the user data, and display
the corresponding view?

To implement the requirement of


handling user action like a click of
a button or link and to respond to
these requests by displaying the
expected output, server-side
languages like Java/JSP can be
Server-side languages have certain
limitations :-
Multiple request-response cycles to
handle multiple user requests
More network bandwidth consumption
Increased response time
If client-side scripting language JavaScript
 The home page of MyMovie.com contains
the SignUp link. The user performs click
action on this link.
 The user action is handled on the client
side itself with the help of the JavaScript
code. This code arrives on the client along
with the home page of the application.
Advantages of using
JavaScript
No need for back and forth request-
response cycles
Less network bandwidth consumption
In comparison to Java: JavaScript
provides a 35% decrease in average
response time and Pages being
served 200ms faster.
What is JavaScript?
JavaScript is the programming
language for web users to convert
static web pages to dynamic web
pages.
Web page designed using HTML
and CSS is static.
JavaScript
combined with HTML and
CSS makes it dynamic.

JavaScriptwas created as a scripting


language in 1995 over the span of
10 days with the name 'LiveScript'.
Now, JavaScript is a full-fledged
programming language because of
its huge capabilities for developing
web applications.
It contains core language features like
control structures, operators,
statements, objects, and functions.
JavaScript is an interpreted language.
The browser interprets the JavaScript
code embedded inside the web page,
executes it, and displays the output. It
is not compiled to any other form to
be executed.
Where to write JavaScript code?

 JavaScript code can be embedded


within the HTML page or can be written
in an external file.
 There are three ways of writing
JavaScript depending on the platform :
 Inline Scripting
 Internal Scripting
 External Scripting
Internal Scripting
When JavaScript code are written
within the HTML file itself, it is called
internal scripting.
Internal scripting, is done with the help
of HTML tag : <script> </script>
This tag can be placed either in the
head tag or body tag within the HTML
file.
 JavaScript code  JavaScript
written inside code written inside
<body> element is <head> element is
as shown below : as shown below :
<html> <html>
<head> <head>
</head> <script>
<body> //internal script
<script> / </script>
/internal script </head>
</script> <body>
</body> </body>
</html> </html>
External Scripting
JavaScript code can be written in an
external file also and is saved with
the extension *.js (e.g. fileName.js)
To include the external JavaScript
file, the script tag is used with
attribute 'src‘.
<html>
<head>
<!-- *.js file contain the JavaScript
code --> <script src="*.js">
</script></head>
<body></body></html>
Example
Demo.js :-
let firstName="Rexha";
let lastName="Bebe";
console.log(firstName+" "+lastName);
Demo.html :-

<html><head>
<script src="Demo.js"></script>
</head>
<body></body></html>
NOTE: In external file, JavaScript code
is not written inside <script>
</script> tag.
Environmental Setup - Internal

To work with JavaScript, you can


use
Editor

(Notepad, Visual Studio Code


IDE etc.)
Browser

(Google Chrome, Microsoft Edge


Steps to execute JavaScript code
Open Visual Studio Code from
your start menu.
Once Visual Studio Code is launched,
Go to the File menu in the Menu bar,
select the New File option.
 Create the below-mentioned two files (index.js and
index.html) and type the below-given code.
index.js file:
console.log("This content is from external JavaScript
file");
index.html
<html>
<head>
<title>JavaScript Introduction</title>
<script>
console.log("This content is from script tag within
<head> tag");
</script>
</head>
<script src="index.js"></script>
<body>
</body>
Output:
For the output, copy the
index.html file path into the
browser. Go to the developer tool
in the browser, there in the
console option, the output is as
shown below:
 In the above example, to render the
HTML file, the path of the HTML file is
copied into the browser. But in this
case, each time any changes are done
in the code the page must be
refreshed for the changes to reflect.
 The Visual Studio Code provides an
option to add extensions to render the
code in a server.
Adding Live Server

Any changes that developers


make further will be
automatically detected and
rendered properly.
Adding Live Server:
1. Go to the extension tab in
Visual Studio Code and search for
Live Server and click on the
Once it gets installed, there will be a
screen with an uninstall button option
as shown below and the Live Server is
ready to render the HTML pages.
To render an HTML page, right-
click on the intended HTML page in
the Explore tab and select the
‘Open with Live Server’ option.
Need for Linting
 Linting is the process of analyzing the
code during development stage to
notify the issues or errors in the code.
 This helps developer to quickly fix the
issues during development and
thereby improving the code quality.
 ESLint is one of the linting tool used
for JavaScript.
Adding ESLint plugin in VS Code
IDE:
Open Visual Studio Code, go to the
extension, search for “ESLint”.
Once the ESLint extension
appears, hit the “Install” button as
shown below:
Afterthe installation of ESLint,
below screen will be visible:
Adding ESLint using NPM

In order to display the code issues


dynamically in the console, we need to
install eslint node module from npm
repository.
Node.js software needs to be installed
in system in order to use npm.
Node.js is a JavaScript runtime
environment that executes the
JavaScript code outside a web browser.
It has a default package manager
called Node Package Manager
(npm) which gets installed
automatically along with Node.js
installation.
npm can be used to install any
third-party JavaScript libraries.
Here, we are using npm to install
Following are the steps to configure
ESLint with JavaScript.
Create a JavaScript demo.js file
with below sample code
let firstName="Rexha"
let lastName ="Bebe";
for( let i=0;i<=5;i--){
console.log(i);
 Go to the Terminal in the VS code IDE,
be in project folder (where the
demo.js file is present) path.
 Run the below command
npm init
 The above command creates
a package.json file which will have
the metadata and package
dependencies for the project.
Now install ESLint using the
following command:
npm install eslint --save-dev
Next, is to create the configuration
file: “.eslintrc.js”, using one of the
below-given command:
./node_modules/.bin/eslint --init
OR
npm init @eslint/config
This command will prompt
questions on how ESLint is to be
used and completes the creation
of a configuration file for ESLint.
If any linting issue occurs in code,
all the issues will be highlighted
and more details will be provided
in the console as shown below.
Identifiers
Identifiers are those names that
help in naming the elements in JavaScript.
 Examples: firstName; placeOfVisit;
Identifiers should follow below rules:
 The first character of an identifier should
be letters of the alphabet or an underscore
(_) or dollar sign ($).
 Subsequent characters can be letters of
alphabets or digits or underscores (_) or a
dollar sign ($).
 Identifiers are case-sensitive. Hence,
firstName and FirstName are not the same.
 Reserved keywords are part of
programming language syntax and cannot
Type of Identifiers
The specific type is based on:
The data which an identifier will
hold and
The scope of the identifier
Let
An identifier declared using ‘let’
keyword has a block scope i.e., it is
available only within the block in
which it is defined.
The value assigned to the identifier
can be done either at the time of
declaration or later in the code and
can also be altered further.
Let

 As a best practice, use the let keyword for


identifier declarations that will change
their value over time or when the variable
need not be accessed outside the code
block.
 For example, in loops, looping variables
can be declared using let as they are
never used outside the block.
Example
letname="William";
console.log("Welcome to JS course,
Mr."+ name);

let name = "Goth";


/* This will throw an error because the
identifier 'name' has been already
declared and we are redeclaring the
variable, which is not allowed using the
'let' keyword. */
console.log("Welcome to JS course,
Mr."+name);
Const
The identifier to hold data that does
not vary is called 'Constant' and to
declare a constant, 'const' keyword
is used, followed by an identifier.
The value is initialized during the
declaration itself and cannot be
altered later.
The identifiers declared using 'const'
keyword have block scope i.e., they
exist only in the block of code
within which they are defined.
Example
const pi = 3.14;
console.log("The value of Pi is:
"+pi);

pi = 3.141592;
/* This will throw an error because
the assignment to a const needs
to be done at the time of
declaration and it cannot be re-
initialized. */
console.log("The value of Pi is:
Var
 The identifiers declared to hold data
that vary are called 'Variables' and
to declare a variable, the 'var'
keyword is optionally used.
 Once the value is initialized, it can be
modified any number of times later in
the program.
 It takes the Function scope i.e., it is
globally available to the Function
within which it has been declared and
it is possible to declare the identifier
name a second time in the
same function.
Example
var name = "William";
console.log("Welcome to JS course, Mr." +
name);
var name = "Goth";

/* Here, even though we have redeclared the


same identifier, it will not throw any error.*/
console.log("Welcome to JS course, Mr." +
name);
let vs. const vs. var
Data types
 It is mandatory for a programming
language to know the type of value or the
type of data that the variable holds.
 The operations or manipulations that must
be applied on a variable will be specific to
the type of data that a variable will hold.
 For example, the result of add operation
on two variables will vary based on the
data types i.e. numeric or textual.
Data types
 Data type mentions the type of value
assigned to a variable.
 In JavaScript, the type is not defined during
variable declaration. Instead, it is determined
at run-time based on the value it is initialized
with.
 Hence, JavaScript language is
a loosely typed or dynamically typed languag
e.
Also, there can be same variable
of different types in JavaScript
code based on the value that is
assigned to it.
For example, if let age = 24, the
variable 'age' is of type number.
But if, let age = "Twenty-Four",
variable 'age' is of type string.
Example:
let age = 24; //number
let name = “Tom” //string
let qualified = true; //boolean
Primitive Data types
The data is said to be primitive if it
contains an individual value.
1. Number:
To store a variable that holds a
numeric value, the primitive data
type number is used.
A number data type gets classified
as shown below:
Number
But in JavaScript, the data type
number is assigned to the values of
type integer, long, float, and double.
For example, the variable with
number data type can hold values
such as 300, 20.50, 10001, and
13456.89.
Example:
const pi = 3.14; // its value is 3.14
const smallestNaturalNumber = 0;

// its value is 0
In JavaScript, any other value that
does not belong to the above-
mentioned types is not considered as a
legal number.
Such values are represented
as NaN (Not-a-Number).
Example:
let result = 0/0; // its value is NaN
let result = "Ten" * 5; //its value is NaN
String
When a variable is used to store
textual value.
String values are written in
quotes, either single or double.
Example:

let personName= “Rexha”;


 //OR
let personName = ‘Rexha’; // both
String
Strings containing single quotes must
be enclosed within double quotes and
vice versa.
Example:
let ownership= "Rexha's"; //OR
let ownership = 'Rexha"s';
This will be interpreted as Rexha's
and Rexha"s respectively. Thus, use
opposite quotes inside and outside of
JavaScript single and double quotes.
But if you use the same quotes
inside a string and to enclose the
string:
Example:
let ownership= "Rexha"s"; //OR
let ownership = 'Rexha's';
It is a syntax error.
Thus, remember, strings containing
single quotes must be enlosed within
double quotes and strings containing
double quotes must be enclosed
within single quotes.
To access any character within the
string, it is important to be aware
of its position in the string.
The first character exists at index
0, next at index 1, and so on.
Literals
let firstName="Kevin";
let lastName="Patrick";
console.log("Name:"+firstName+”
”+ lastName+”\
nEmail:”+firstName+"_"+
lastName+ "@abc.com");
/*OUTPUT:Name: Kevin Patrick
Email:Kevin_Patrick@abc.com *
/
Here, '+' is used for concatenation
of identifiers and static content, and
'\n' for a new line.
 To get the same output, literals can be used
as shown below:
 let firstName="Kevin";
 let lastName="Patrick";
 console.log(`Name:${firstName} $
{lastName}Email: ${firstName}_$
{lastName}@abc.com`); /*OUTPUT:Name:
Kevin Patrick
Email:Kevin_Patrick@abc.com */
 Using template literal, multiple lines can be
written in the console.log() in one go.
 So, the template literal notation enclosed in
``(backticks) makes it convenient to have
multiline statements with expressions and
the variables are accessed using ${}
notation.
Boolean

Boolean is a data type which


represents only two values: true and
false.
Values such as 100, -5, “Cat”, 10<20,
1, 10*20+30, etc. evaluates
to true whereas 0, “”, NaN, undefined,
null, etc. evaluates to false.
Undefined
 When the variable is used to store "no
value", primitive data type undefined is used.
Example 1:
 let custName;

// here value and the data type are undefined


 The JavaScript variable can be made empty
by assigning the value undefined.
Example 2:
 let custName = "John";

// here value is John and the data type is


String
 custName = undefined;

// here value and the data type are undefined


null
The null value represents "no
object".
Example:
let item = null;
// variable item is intended to be
assigned with object later. Hence
null is assigned during variable
declaration.
If required, the JavaScript variable
can also be checked if it is
pointing to a valid object or null.
BigInt
 BigInt is a special numeric type that provides
support for integers of random length.
 A BigInt is generated by appending n to the
end of an integer literal or by calling the
function BigInt that generates BigInt from
strings, numbers, etc.
 Example:

const bigintvar =
674234782346898878947474723894778236
47n; OR
const bigintvar =
BigInt("674234782346898878947474723894
77823647");
const bigintFromNumber = BigInt(10);
common math operations can be
done on BigInt as regular numbers.
But BigInt and regular numbers
cannot be mixed in the expression.
Example:
alert(3n + 2n); // 5
alert(7n / 2n); // 3
alert(8n + 2); // Error: Cannot mix
BigInt and other types
Here the division returns the result
rounded towards zero, without the
decimal part. Thus, all operations on
BigInt return BigInt.
 BigInt and regular numbers must
be explicitly converted using
either BigInt() or Number().
 Example:
 let bigintvar = 6n;
 let numvar = 3;
 // number to bigint
 alert(bigintvar + BigInt(numvar)); // 9
 // bigint to number
 alert(Number(bigintvar ) + numvar); // 9
 In the above example, if the bigintvar is
too large that it won’t fit the number
type, then extra bits will be cut off.
Talking about comparison and
boolean operations on BigInt, it
works fine.
Example:
alert( 8n > 2n ); // true
alert( 4n > 2 ); // true
Even though numbers and BigInts
belong to different types, they can
be equal ==, but not strictly
equal ===.
Example:
alert( 5 == 5n ); // true
alert( 5 === 5n ); // false
 When inside if or other boolean
operations, BigInts behave like numbers.
Example:
 if (0n) { // never executes}
 BigInt 0n is falsy, other values are
considered to be truthy.
 Boolean operators, such as ||, && and
others also work perfectly with Bigint’s
similar to numbers.
 Example:
 alert( 1n || 2 ); // 1, here 1n is considered
truthy
 alert( 0n || 2 ); // 2, here 0n is considered
falsy
Non-Primitive data types
 The data type is said to be non-primitive
if it is a collection of multiple values.
 The variables in JavaScript may not
always hold only individual values, there
are times a group of values are
stored inside a variable.
 JavaScript gives non-primitive data types
named Object and Array, to implement
this.
Objects
Objects in JavaScript are a collection
of properties and are represented in
the form of [key-value pairs].
The 'key' is a string or a symbol and
should be a legal identifier.
The 'value‘ can be any JavaScript
value like Number, String, Boolean, or
another object.
JavaScript provides the number of
built-in objects as a part of the
language and user-defined JavaScript
objects can be created using object
literals.
Syntax:

{
key1 : value1,
key2 : value2,
key3 : value3
};
 Example:
let mySmartPhone ={
name: "iPhone",
brand: "Apple",
platform: "iOS",
price: 50000 };
Array
To store an ordered collection,
which cannot be achieved using
the objects.
There are two ways of creating an
array:

let dummyArr = new Array();


Array
Either array can be declared as
empty and can be assigned with
value later, or can have the value
assigned during the declaration.
Example:

digits =[1,2,3,"four"];
A single array can hold multiple
values of different data types.
SCREEN OUTPUT AND KEYBOARD
INPUT
ALERT BOX:
 Alert box is a very frequently useful to send or
write cautionary messages to end user screen.
 Alert box is created by alert method of window
object as shown below.
Syntax: window. alert (“message”);
 When alert box is popup, the user has to click
ok to continue browsing or to perform any
further operations.
<head>
<script language="JavaScript">
function add( )
{
a=20;
b=40;
c=a+b;
window.alert("This is for addition of 2
no's");
document.write("Result is: "+c);
}
</script>
</head>
<body onload="add( )">
If you press OK, then prints
output as:
Result is 60.
CONFIRM POPUP BOX
 This is useful to verify or accept something
from user. It is created by confirm method
of window object as shown below.
Syntax:- window.confirm
(“message?”);
 When the confirm box pop’s up, user must
click either ok or cancel buttons to proceed.
If user clicks ok button it returns the
boolean value true. If user clicks cancel
button, it returns the boolean value false.
<head>
<script>
function sub( ) {
a=50; b=45;
c=a-b;
x=window.confirm("Do you want to see subtraction of
numbers");
if(x==true) {
document.write("result is :"+c);
}
else {
document.write("you clicked cancel button");
}
}
</script>
</HEAD>
<BODY onload="sub( )"> To see the o/p in pop up box:
When you click on OK button, it
will display result as: Result is: 5
When you click on Cancel button,
the control is returned to the
browser.
PROMPT POPUP BOX
 To accept data from keyboard at runtime. Prompt
box is created by prompt method of window
object.

Syntax: window.prompt (“message”,


“default text”);

 When prompt dialog box arises user will have to


click either ok button or cancel button after
entering input data to proceed. If user click ok
button it will return input value. If user click
cancel button the value ―null will be returned.
<script>
function fact( )
{
var b=window.prompt("enter +ve
integer :","enter here");
var c=parseInt(b);
a=1;
for(i=c;i>=1;i--)
{
a=a*i;
}
window.alert("factorial value :"+a);
}
</script>
</HEAD>
<BODY onload="fact( )">
</BODY>
Write ( ) Method:
 To write some content or JavaScript code
in a Document.
Syntax: document. write (exp1, exp2,
exp3, ...);
 Here, exp1, exp2, exp3 ….. are all
optional arguments.
 The writeln() method is identical to the
document.write() method, with the
addition of writing a newline character
<body>
<p>Note that write() does NOT add a
new line after each statement:</p>
<script>
document.write("Hello World!");
document.write("Have a nice day!");
</script>
<p>Note that writeln() add a new line
after each statement:</p>
<script>
document.writeln("Hello World!");
document.writeln("Have a nice day!");
</script>
</body>
Output:

Note that write() does NOT add a


new line after each statement:
Hello World!Have a nice day!
Note that writeln() add a new line
after each statement:
Hello World!
Have a nice day!
Operators
 The symbols used to perform operations on
the values.
 Operands: Represents the data.
 Operator: Performs certain operations
on the operands.
 let sum = 5 + 10;
 The statement formed using the operator
and the operands are called Expression.
 In the above example, 5+10 is an
expression.
 The values are termed as operands.
 The symbol ‘+’ is the operator which
indicates which operation needs to be
performed.
Types of Operators

Operators are
categorized into unary, binary, and
ternary based on the number of
operands on which they operate in
an expression.
Arithmetic Operators
Arithmetic operators are used for
performing arithmetic operations.
let sum = 5 + 3; // sum=8
let difference = 5 – 3; // difference=2
let product = 5 * 3; // product=15
let division = 5/3; // division=1
let mod = 5%3; // mod=2
let value = 5;
value++; // increment by 1, value=6
let value = 10;
value--; // decrement by 1, value=9
Arithmetic Operators –
String Type Operands

Arithmetic operator '+' when used with


string type results in the concatenation.
let firstName = "James";
let lastName = "Roche";
let name = firstName + " " +
lastName;
// name = James Roche
 Arithmetic operator ‘+’ when used
with a string value and a numeric
value, it results in a new string value.
let strValue="James";
let numValue=10;
let newStrValue= strValue + " " +
numValue; //newStrValue=James10
Assignment Operators
 Assignment operators are used for assigning
values to the variables.

 let num = 30; // num=30


 let num += 10; // num=num+10 => num=40
 let num -= 10; // num=num-10 => num=20
 let num *= 30; // num=num*30 => num=900
 let num /= 10; // num=num/10 => num=3
 let num %= 10; // num=num%10 => num=0
Relational or Comparison
Operators
Used for comparing values and the
result of comparison is always
either true or false.
Relational operators shown below
do implicit data type conversion of
one of the operands before
comparison.
 10 > 10; //false
 10 >= 10; //true
 10 < 10; //false
 10 <= 10; //true
 10 == 10; //true
 10 != 10; //false
 Relational operators shown below
compares both the values and the value
types without any implicit type
conversion.
Strict equality (===) and strict
inequality (!==) operators consider
only values of the same type to be
equal.
Hence, strict equality and strict
inequality operators are highly
recommended to determine whether
two given values are equal or not.
As a best practice, you should use
=== comparison operator when you
want to compare value and
type, and the rest of the places for
value comparison == operator can be
used.
Logical Operators
To make a decision based on
multiple conditions. Each operand
is considered a condition that can
be evaluated to true or false.
Logical Operators

!(10 > 20); //true

(10 > 5) && (20 > 20); //false

(10 > 5) || (20 > 20); //true


typeof Operator
 JavaScript is a loosely typed language
i.e., the type of variable is decided
at runtime based on the data assigned
to it. This is also called dynamic data
binding.
 The typeof operator can be used to find
the data type of a JavaScript variable.
typeof "JavaScript World" //string
typeof 10.5 // number
typeof 10 > 20 //boolean
typeof undefined //undefined
typeof null //Object

Statements
 Statements are instructions in JavaScript
that have to be executed by a web browser.
 JavaScript code is made up of a sequence
of statements and is executed in the same
order as they are written.
A Variable declaration is the simplest
example of a JavaScript statement.
 Syntax:

 var firstName = "Newton" ;


Other types of JavaScript statements
include conditions/decision making,
loops, etc.
White (blank) spaces in statements
are ignored.
It is optional to end each JavaScript
statement with a semicolon.
Expressions
 While writing client-logic in JavaScript,
variables and operators are often combined to
do computations. This is achieved by writing
expressions.
10 + 30; //Evaluates to numeric value
"Hello" + "World"; //Evaluates to string value
itemRating > 5; //Evaluates to boolean value
(age > 60)? "Senior citizen": "Normal citizen";
/
*Evaluates to one string value based on whethe
r condition is true or false. If the condition
evaluates to true then the first string value
"Senior citizen" is assigned otherwise the
second string value is assigned
"Normal citizen" */
Types of Statements
Conditional Statements: help you
to decide based on certain conditions.
These conditions are specified by a set
of conditional statements
having boolean expressions that are
evaluated to a boolean value true or
false.
Non-Conditional Statements:
Non-Conditional statements are
those statements that do not need any
condition to control the program
execution flow.
Types of Non-Conditional
Statements
Non-Conditional statements are
those statements that do not need
any condition to control the
program execution flow.
Comments
Used to prevent the execution of a
certain lines of code and to
add information in the code that
explains the significance of
the line of code being written.
Example

// Formula to find the area of a circle giv

en its radius

var areaOfCircle = 2 * pi * radius;

/*Formula to find the area of a circle

based on given its radius value.*/


Break Statement
While iterating over the block of
code getting executed within the
loop, the loop may be required to
be exited if certain condition is
met.
The 'break' statement is used to
terminate the loop and transfer
control to the first statement
following the loop.
Syntax:
break;
Example- for loop with
five iterations which
increment variable "counter".
When loop counter = 3, loop
terminates.
Also, shown below is the value of the
counter and loopVar for every iteration
of the loop.
var counter = 0;
for (var loop = 0; loop < 5; loop++) {
if (loop == 3)
break;
counter++;
}
Continue Statement
Continue statement is used to
terminate the current iteration of
the loop and continue execution of
the loop with the next iteration.
Syntax:
continue;
Example- for loop with five
iterations which
increment variable "counter".
When loop counter = 3, the
current iteration is skipped and
moved to the next iteration.
var counter = 0;
for (var loop = 0; loop < 5; loop++) {
if (loop == 3)
continue;
counter++;
}
Types of Conditional Statements
Conditional statements help in
performing different actions for
different conditions.
It is also termed as decision-
making statements.
JavaScript supports two decision-
making statements:
Ternary operator
It is a conditional operator that evaluates
to one of the values based on whether the
condition is true or false.
It is a shortcut of 'if-else' condition.
Example:

let workingHours = 9.20;


let additionalHours;
(workingHours > 9.15) ? additionalHours =“
You have positive additional hours” :
additionalHours = “You have negative
additional hours”;
console.log(additionalHours);
If Statements
 The 'if' statement evaluates the
expression given in its
parentheses giving a boolean value as
the result.
 You can have multiple 'if' statements
for multiple choice of
statements inside an 'if' statement.
 There are different flavors of if-else
statement:
 Simple 'if' statement
 if -else
 if–else–if ladder
if statement
 Toexecute a block of code if the given condition
evaluates to true.
 Syntax:

if (condition) {
// block of code that will be
executed, if the condition is true
}
 Example:

let num1 = 12;


if (num1 % 2 == 0) {
console.log("It is an even number!!");
}
// OUTPUT: It is an even number!! Because 12%2
If-else
The 'else' statement is used to execute a
block of code if the given condition
evaluates to false.
Syntax:
if (condition) {
// block of code that will be
executed, if the condition is true
}
else { // block of code that will be
executed, if the condition is false
}
Example
let num1 = 1;
if (num1 % 2 == 0) {
console.log("It is an even number!!");
}
else{
console.log("It is an odd number!!");
}
//
OUTPUT: It is an odd number!! Because
in if 1%2 evaluates to false and moves
to else condition
If-else-if Ladder
if...else ladder is used to check for a new condition when the
first condition evaluates to false.
Syntax:
if (condition1) {
// block of code that will be
executed if condition1 is true
}
else if (condition2) {
// block of code that will be
executed if the condition1 is false and condition2 is tr
ue
}
else {
// block of code that will be
executed if the condition1 is false and condition2 is f
alse
}
Example
let marks = 46;
if (marks >= 85) {
console.log("Very Good");
}
else if (marks < 85 && marks >= 50)
{
console.log("Good");
}
else {
console.log("Needs Improvement");
}
 // OUTPUT: Needs Improvement, Because the
value of marks is 46 which doesn't satisfy the
first two condition checks.
Switch Statement
 The Switch statement is used to select and
evaluate one of the many blocks of code.
Syntax:
switch (expression) {
case value 1: code block;
break;
case value 2: code block;
break;
case value N: code block;
break;
default: code block;
}
 'break' statement is used to come out of the
switch and continue execution of statement(s)
the following switch.
Switch Statement - with break
statement
 For the given Employee performance rating (between
1 to 5), displays the appropriate performance badge.
var perfRating = 5;
switch (perfRating) {
case 5: console.log("Very Poor");
break;
case 4: console.log("Needs Improvement");
break;
case 3: console.log("Met Expectations");
break;
case 2: console.log("Commendable");
break;
case 1: console.log("Outstanding");
break;
default: console.log("Sorry!! Invalid Rating.");
}
OUTPUT: Very Poor
Switch Statement - without break
statement
var perfRating = 5;
switch (perfRating) {
case 5: console.log("Very Poor");
case 4: console.log("Needs Improvement");
case 3: console.log("Met Expectations");
case 2: console.log("Commendable");
case 1: console.log("Outstanding");
default: console.log("Sorry!! Invalid Rating.");
}
/*
OUTPUT:
Very Poor
Needs Improvement
Met Expectations
Commendable
Outstanding
Sorry!! Invalid Rating.
*/
 The reason for the above output is, initially
perfRating is checked against case 5 and it
got matched, hence ‘Very Poor’ is displayed.
But as the break statement is missing, the
remaining cases including default got
executed.
Switch Statement - default
statement
var perfRating = 15;
switch (perfRating) {
case 5: console.log("Very Poor"); break;
case 4: console.log("Needs Improvement"); brea
k;
case 3: console.log("Met Expectations"); break;

case 2: console.log("Commendable"); break;


case 1: console.log("Outstanding"); break;
default: console.log("Sorry!! Invalid Rating.");
}
/* OUTPUT: Sorry!! Invalid Rating. */
Here perfRating = 15 does not match any case va
lues. Hence, the default statement got executed.
Loops
 In JavaScript code, specific actions may have to be
repeated a number of times.
 For example, consider a variable counter which has to
be incremented five times.
 To achieve this, increment statement can be written
five times as shown below:
let counter = 0;
/* Same statement repeated 5 times */
counter++;
counter++;
counter++;
counter++;
counter++;
 Looping statements in JavaScript helps to execute
statement(s) required number of times without
repeating code.
 Best Practice: Avoid heavy nesting inside the loops.
For Loop
'for'
loop is used when the block of
code is expected to execute for a
specific number of times. To
implement it, use the following
syntax.
 Example: incrementing variable
counter five times using 'for' loop:
let counter = 0;
for (let loopVar = 0; loopVar < 5;
loopVar++) { loopVar Counter
0 1
counter = counter + 1; 1 2
console.log(counter); 2 3
3 4
} 4 5
Here, in the above loop
let loopVar=0; // Initialization
loopVar < 5; // Condition
loopVar++; // Update
counter = counter + 1; // Action
While Loop
'while' loop is used when the block of
code is to be executed as long as the
specified condition is true.

The value for the variable used in


the test condition should be updated
inside the loop only.
 Example: Incrementing variable counter five
times using a 'while' loop.
let counter = 0; loopVar counter
let loopVar = 0;
0 1
while (loopVar < 5) {
1 2
console.log(loopVar);
2 3
counter++;
3 4
loopVar++;
4 5
console.log(counter);
}
 Here, in the above loop
 let counter=0; // Initialization
 let loopVar=0; // Initialization
 loopVar < 5; // Condition
 loopVar++; // Update
 counter++; // Action
Do-While Loop
 'do-while'is a variant of 'while' loop.
 This will execute a block of code once
before checking any condition.
 Then, after executing the block it will
evaluate the condition given at the end of
the block of code.

 The value for the variable used in the test


condition should be updated inside the loop
only.
 Example: incrementing variable counter five
times using 'do-while' loop:
let counter = 0;
let loopVar = 0;
do { loopVar counter
console.log(loopVar); 0 1
counter++; 1 2
loopVar++; 2 3
console.log(counter); 3 4
} 4 5
while (loopVar < 5);
 Here, in the above loop
 let counter=0; // Initialization
 let loopVar=0; // Initialization
 loopVar < 5; // Condition
 loopVar++; // Update
Thank You

You might also like