0% found this document useful (0 votes)
8 views61 pages

JavaScript Part II

The document provides an overview of JavaScript operators, categorizing them into unary, binary, and ternary types based on the number of operands. It details various unary operators such as increment, decrement, and typeof, along with binary arithmetic and relational operators. Examples illustrate how these operators function in JavaScript, including their behavior with different data types.

Uploaded by

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

JavaScript Part II

The document provides an overview of JavaScript operators, categorizing them into unary, binary, and ternary types based on the number of operands. It details various unary operators such as increment, decrement, and typeof, along with binary arithmetic and relational operators. Examples illustrate how these operators function in JavaScript, including their behavior with different data types.

Uploaded by

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

Web Technology

JavaScript

Dr. Navanath Saharia


Indian Institute of Information Technology Senapati, Manipur
nsaharia@[Link]

nsaharia@[Link] JavaScript 1 / 32
Operator Operator

Operator

b An operator is a special symbol or keyword used to perform an operation on one or more operands
and return a result

b An operand is what operators are applied to. For example, 5 times 2 contains two operands, 5 and 2
and one ’×’ operator

nsaharia@[Link] JavaScript 2 / 32
Operator Operator

Operator

b An operator is a special symbol or keyword used to perform an operation on one or more operands
and return a result

b An operand is what operators are applied to. For example, 5 times 2 contains two operands, 5 and 2
and one ’×’ operator

b Based on number of operands, JavaScript operators can be classified into three classes

- Unary - Operator is applied on one operand. Example: typeof

- Binary - Operator is applied on two operands. Example: +

- Ternary or tertiary - Operator is applied on three operands. Example: ? :

nsaharia@[Link] JavaScript 2 / 32
Operator Unary Operator

Unary Operator - I
b Increment (++): Adds 1 to its operand.
let abc = 123; [Link](++abc); //output: 124
b Decrement (--): Subtracts 1 from its operand.
let abc = 123; [Link](--abc); //output: 122
b Unary plus (+) operator : Attempts to convert its operand to number, if it is not already.
[Link](+''); //output: 0
[Link](+"10" +" " + typeof(+"10")); //output: 10 number
[Link](+true); //output: 1
[Link](+'hello'); //output: NaN
b Unary minus/negation (-): Negates its operand
const a = '123'; [Link](a); //output: 123
const b = -a; [Link](b); //output: -123
b Logical not (!): Inverts the truth value of its operand.
let abc = false; let bcd = ! abc; [Link](bcd); //output: true
b Bitwise not (∼): Inverts the bits of its operand. It operates on the binary number.
let abc = 123; [Link](~abc); //output: -124
nsaharia@[Link] JavaScript 3 / 32
Operator Unary Operator

Unary Operator - II
b typeof operator returns a string indicating the type of the operand’s value.
[Link](typeof true); //output: boolean
[Link](typeof "abc"); //output: string

nsaharia@[Link] JavaScript 4 / 32
Operator Unary Operator

Unary Operator - II
b typeof operator returns a string indicating the type of the operand’s value.
[Link](typeof true); //output: boolean
[Link](typeof "abc"); //output: string
b instanceof operator tests to see if the prototype property of a constructor appears anywhere in the
prototype chain of an object. The return value is a boolean
function Student(rollNo, stdName, curSem, cGI){
[Link] = rollNo; [Link] = stdName; [Link] = curSem; [Link] = cGI;}
const std = new Student('17010101', 'Abc Kumar', 4, 6.8);
[Link]([Link]);//output: 6.8
[Link](std instanceof Student);//output: true

nsaharia@[Link] JavaScript 4 / 32
Operator Unary Operator

Unary Operator - II
b typeof operator returns a string indicating the type of the operand’s value.
[Link](typeof true); //output: boolean
[Link](typeof "abc"); //output: string
b instanceof operator tests to see if the prototype property of a constructor appears anywhere in the
prototype chain of an object. The return value is a boolean
function Student(rollNo, stdName, curSem, cGI){
[Link] = rollNo; [Link] = stdName; [Link] = curSem; [Link] = cGI;}
const std = new Student('17010101', 'Abc Kumar', 4, 6.8);
[Link]([Link]);//output: 6.8
[Link](std instanceof Student);//output: true
b void operator is used to explicitly return undefined value. It is useful particularly when working
with the Web API, to ensure that the result of an expression is consistently undefined
function abc(a,b) { return a*b;}
[Link](abc(2,3)); //output: 6
[Link](void abc(2,3)); //output: undefined
void 0; void(1); void 'hello'; void {}; void []; //output: undefined
nsaharia@[Link] JavaScript 4 / 32
Operator Unary Operator

Unary Operator - III

b in operator tests if a string or symbol property is present in an object. Returns boolean


const student = {rollNo: 101, stdName: "Abc Bcd", curSem: 4}
[Link]('rollNo' in student); //output: true

nsaharia@[Link] JavaScript 5 / 32
Operator Unary Operator

Unary Operator - III

b in operator tests if a string or symbol property is present in an object. Returns boolean


const student = {rollNo: 101, stdName: "Abc Bcd", curSem: 4}
[Link]('rollNo' in student); //output: true

b delete operator removes a property from an object. On successful deletion, it will return true, else
false will be returned
delete [Link]; [Link]([Link]); //output: undefined
if ('rollNo' in student === false) {[Link] = '102';}
[Link]([Link]); //output: 102

nsaharia@[Link] JavaScript 5 / 32
Operator Unary Operator

Unary Operator - III

b in operator tests if a string or symbol property is present in an object. Returns boolean


const student = {rollNo: 101, stdName: "Abc Bcd", curSem: 4}
[Link]('rollNo' in student); //output: true

b delete operator removes a property from an object. On successful deletion, it will return true, else
false will be returned
delete [Link]; [Link]([Link]); //output: undefined
if ('rollNo' in student === false) {[Link] = '102';}
[Link]([Link]); //output: 102

b new operator allows developers create an instance of a user-defined object type or built-in object
types that has a constructor
function Student(rollNo, stdName){[Link] = rollNo; [Link] = stdName;}
const std = new Student(103, 'Amar Akbar Anthony');
[Link]([Link]); //output: Amar Akbar Anthony

nsaharia@[Link] JavaScript 5 / 32
Operator Unary Operator

Unary Operator - IV

b yield operator is used to pause and resume a generator function


function* abc(i) { while (i < 100) { yield i; i++; } }
const iterator = abc(5);
[Link]([Link]().value); //output: 5
[Link]([Link]().value); //output: 6

nsaharia@[Link] JavaScript 6 / 32
Operator Unary Operator

Unary Operator - IV

b yield operator is used to pause and resume a generator function


function* abc(i) { while (i < 100) { yield i; i++; } }
const iterator = abc(5);
[Link]([Link]().value); //output: 5
[Link]([Link]().value); //output: 6

b yield* is used to delegate iteration of the current generator to an underlying iterator. It iterates over
the operand and yields each value returned by it. Besides generator objects, yield* can also yield
other kinds of iterables (e.g., arrays, and strings)
function* abc() { yield "output of 1st yield"; yield* [1,2,3]}
function* bcd() { yield* abc(); }
const iterator = bcd();
[Link]([Link]().value); //output: "output of 1st yield"
[Link]([Link]().value); //output: 1
[Link]([Link]().value); //output: 2

nsaharia@[Link] JavaScript 6 / 32
Operator Binary Operator

Arithmatic/Math Operator

b Addition (+): Produces the sum of numeric operands or string concatenation


- let abc = 5, bcd = -abc; [Link](abc+bcd);
- let abc = "abc", bcd = 2; [Link](abc+bcd); //output: abc2
- let abc = true, bcd = 2; [Link](abc+bcd);//output: 3

b Subtraction (-): Subtracts the two operands, producing their difference


- let abc = 5, bcd = -abc; [Link](abc-bcd);
- let abc = "abc", bcd = 2; [Link](abc-bcd, bcd-abc); //output: NaN NaN
- let abc = true, bcd = 2; [Link](abc-bcd, bcd-abc);//output: -1 1

b Multiplication (*): Produces the product of the operands


- let abc = 5, bcd = -abc; [Link](abc*bcd);
- let abc = "abc", bcd = 2; [Link](abc*bcd); //output: NaN
- let abc = "2", bcd = 2; [Link](abc*bcd); //output: 4
- let abc = true, bcd = 2; [Link](abc*bcd);//output: 2

nsaharia@[Link] JavaScript 7 / 32
Operator Binary Operator

Arithmatic/Math Operator
b Division (/): Produces the quotient of its operands
- let abc = 5, bcd = -abc; [Link](abc/bcd);
- let abc = "abc", bcd = 2; [Link](abc/bcd); //output: NaN
- let abc = "2", bcd = 2; [Link](abc/bcd); //output: 1
- let abc = true, bcd = 2; [Link](abc/bcd);//output: 0.5

nsaharia@[Link] JavaScript 8 / 32
Operator Binary Operator

Arithmatic/Math Operator
b Division (/): Produces the quotient of its operands
- let abc = 5, bcd = -abc; [Link](abc/bcd);
- let abc = "abc", bcd = 2; [Link](abc/bcd); //output: NaN
- let abc = "2", bcd = 2; [Link](abc/bcd); //output: 1
- let abc = true, bcd = 2; [Link](abc/bcd);//output: 0.5
b Remainder (%): Returns the remainder
- let abc = 5, bcd = -abc + 1; [Link](abc%bcd, bcd%abc);
- let abc = "abc", bcd = 2; [Link](abc%bcd); //output: NaN
- let abc = "3", bcd = 2; [Link](abc%bcd); //output: 1
- let abc = true, bcd = 2; [Link](abc%bcd);//output: 1

nsaharia@[Link] JavaScript 8 / 32
Operator Binary Operator

Arithmatic/Math Operator
b Division (/): Produces the quotient of its operands
- let abc = 5, bcd = -abc; [Link](abc/bcd);
- let abc = "abc", bcd = 2; [Link](abc/bcd); //output: NaN
- let abc = "2", bcd = 2; [Link](abc/bcd); //output: 1
- let abc = true, bcd = 2; [Link](abc/bcd);//output: 0.5
b Remainder (%): Returns the remainder
- let abc = 5, bcd = -abc + 1; [Link](abc%bcd, bcd%abc);
- let abc = "abc", bcd = 2; [Link](abc%bcd); //output: NaN
- let abc = "3", bcd = 2; [Link](abc%bcd); //output: 1
- let abc = true, bcd = 2; [Link](abc%bcd);//output: 1
b Exponentiation (**): Returns the result of raising the 1st operand to the power of the 2nd operand
- let abc = 2, bcd = -abc; [Link](abc**bcd, bcd**abc);
- let abc = 2, bcd = -abc; [Link](abc**(bcd**abc)); //output: 16
- let abc = "3", bcd = 2; [Link](abc**bcd); //output: 9
- let abc = false, bcd = 2; [Link](bcd**abc);//output: 1
nsaharia@[Link] JavaScript 8 / 32
Operator Binary Operator

Relational or Conditional or Comparison Operator


b Greater than (>): Returns true if the left operand is greater than the right, otherwise false
b Less than (<): Returns true if the left operand is less than the right operand, otherwise false
b Both the operator converts its operand to primitive data type starting from the left operand
- If both the operands are string they are compared as string using lexical/dictionary order and
values of the Unicode code points. For example:
/ [Link]('a' > 'A'); will return true, as the Unicode code point value of ‘a’ is
greater than the the Unicode code point value of ‘A’
/ [Link]('a' < 'b'); will return true, due to lexical order and Unicode value

nsaharia@[Link] JavaScript 9 / 32
Operator Binary Operator

Relational or Conditional or Comparison Operator


b Greater than (>): Returns true if the left operand is greater than the right, otherwise false
b Less than (<): Returns true if the left operand is less than the right operand, otherwise false
b Both the operator converts its operand to primitive data type starting from the left operand
- If both the operands are string they are compared as string using lexical/dictionary order and
values of the Unicode code points. For example:
/ [Link]('a' > 'A'); will return true, as the Unicode code point value of ‘a’ is
greater than the the Unicode code point value of ‘A’
/ [Link]('a' < 'b'); will return true, due to lexical order and Unicode value
- Values other than number and string
Operand’s data type Converted to Operand’s data type Converted to
Boolean true 1 undefined NaN
Boolean false 0 null 0

nsaharia@[Link] JavaScript 9 / 32
Operator Binary Operator

Relational or Conditional or Comparison Operator


b Greater than (>): Returns true if the left operand is greater than the right, otherwise false
b Less than (<): Returns true if the left operand is less than the right operand, otherwise false
b Both the operator converts its operand to primitive data type starting from the left operand
- If both the operands are string they are compared as string using lexical/dictionary order and
values of the Unicode code points. For example:
/ [Link]('a' > 'A'); will return true, as the Unicode code point value of ‘a’ is
greater than the the Unicode code point value of ‘A’
/ [Link]('a' < 'b'); will return true, due to lexical order and Unicode value
- Values other than number and string
Operand’s data type Converted to Operand’s data type Converted to
Boolean true 1 undefined NaN
Boolean false 0 null 0
- let abc = 2, bcd = -abc; [Link](abc > bcd); //output: true
- let abc = "abc", bcd = 2; [Link](abc > bcd); //output: false
- let abc = "abc", bcd = "acb"; [Link](abc > bcd); //output: false
- let abc = "3", bcd = 2; [Link](abc > bcd); //output: true
- let abc = false, bcd = 2; [Link](abc < bcd);//output: true
nsaharia@[Link] JavaScript 9 / 32
Operator Binary Operator

Equality Operator

b Equality (==): Tests whether value of the operands are equal. Returns boolean

b Strict equality (===): Tests whether value and type of the operands are equal. Returns boolean

b Inequality (!=) and Strict inequality (!==) are performed just the reverse test of the above.

nsaharia@[Link] JavaScript 10 / 32
Operator Binary Operator

Equality Operator

b Equality (==): Tests whether value of the operands are equal. Returns boolean

b Strict equality (===): Tests whether value and type of the operands are equal. Returns boolean

b Inequality (!=) and Strict inequality (!==) are performed just the reverse test of the above.

b The primary difference is the == operator performs type conversion if the operands are of different
types, however, the === operator does not perform type conversion. For example
- [Link]("2"== 2); will return true, however, [Link]( "2" === 2); will return
false. In the context of == operator, the 1st operand, which is a string is converted to a
number to perform the comparison.
- [Link](true == 1); will return true, however, [Link](true === 1); will return
false. In the context of === operator, the 1st operand, which is a boolean is not converted to a
number to perform the comparison. Thus. it returns false.

b The == operator is less strict and may lead to unexpected results. For example:
[Link](null == undefined); returns true, however null is an object.

nsaharia@[Link] JavaScript 10 / 32
Operator Binary Operator

Bitwise & Shift Operator


b Bitwise AND (&): Performs a bitwise AND operation on its operands.
b Bitwise OR (|): Performs a bitwise AND operation on its operands.
b Bitwise XOR (^): Performs a bitwise XOR operation on its operands.

nsaharia@[Link] JavaScript 11 / 32
Operator Binary Operator

Bitwise & Shift Operator


b Bitwise AND (&): Performs a bitwise AND operation on its operands.
b Bitwise OR (|): Performs a bitwise AND operation on its operands.
b Bitwise XOR (^): Performs a bitwise XOR operation on its operands.
a b a&b a|b a^b
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

nsaharia@[Link] JavaScript 11 / 32
Operator Binary Operator

Bitwise & Shift Operator


b Bitwise AND (&): Performs a bitwise AND operation on its operands.
b Bitwise OR (|): Performs a bitwise AND operation on its operands.
b Bitwise XOR (^): Performs a bitwise XOR operation on its operands.
a b a&b a|b a^b
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
- let a = 5; let b = 3; [Link](a & b); //output 0101 & 0011 = 0001 = 1
- let a = 5; let b = 3; [Link](a | b); //output 0101 | 0011 = 0111 = 7
- let a = 5; let b = 3; [Link](a ^ b); //output 0101 ^ 0011 = 0110 = 6
b Left shift (<<): Shifts the bits of a number to the left by a specified number of positions
b Right Shift (>>): Shifts the bits of a number to the right by a specified number of positions
b Left shifting is equivalent to multiplying by 2, and right shifting is equivalent to dividing by 2.
JavaScript uses 32-bit signed integers for bitwise and shift operations
- let a = 5; let b = 3; [Link](a << b); which is equivalent to
[Link](a * (2 ** b)); //output: 40
nsaharia@[Link] JavaScript 11 / 32
Operator Binary Operator

Logical Operator
b Logical OR (||): Returns true if both the operands are Boolean and one or more of its operands are
true. In the case of non-boolean operands, returns first operand if it is truthy otherwise second
operand.
- [Link](false || true); //output: true
- [Link]("Noble" || "Numbat"); //output: Noble
- [Link](0 || "Numbat"); //output: Numbat

nsaharia@[Link] JavaScript 12 / 32
Operator Binary Operator

Logical Operator
b Logical OR (||): Returns true if both the operands are Boolean and one or more of its operands are
true. In the case of non-boolean operands, returns first operand if it is truthy otherwise second
operand.
- [Link](false || true); //output: true
- [Link]("Noble" || "Numbat"); //output: Noble
- [Link](0 || "Numbat"); //output: Numbat
b Logical AND (&&): Returns true if and only if both the operands are true in the case of Boolean
operands. In the case of non-boolean operands, operator returns the value of the first operand if the
first operand is falsy. If the first operand is truthy, the operator returns the value of the second
operand
- [Link](false && true); //output: false
- [Link]("Noble" && "Numbat"); //output: Numbat
- [Link](0 && "Numbat"); //output: 0
- [Link](true && "Numbat"); //output: Numbat
- [Link](true || false && false); //output: true, because && is executed first
- [Link]((true || false) && false);//output: false, because of ()'s precedence
nsaharia@[Link] JavaScript 12 / 32
Operator Binary Operator

Logical & Comma Operator


b Nullish coalescing (??): Returns its right-hand side operand when its left-hand side operand is
null or undefined, and otherwise returns its left-hand side operand.
- let abc = null ?? 'abc'; [Link](abc); //output: abc
- let bcd = 0 ?? 10; [Link](bcd); //output: 0

nsaharia@[Link] JavaScript 13 / 32
Operator Binary Operator

Logical & Comma Operator


b Nullish coalescing (??): Returns its right-hand side operand when its left-hand side operand is
null or undefined, and otherwise returns its left-hand side operand.
- let abc = null ?? 'abc'; [Link](abc); //output: abc
- let bcd = 0 ?? 10; [Link](bcd); //output: 0
b Short-circuit evaluation of logical operators
- Evaluation of Logical/Boolean operations are terminated as soon as the result is certain.
- [Link]( false && ..... ); is short-circuited to give false
- [Link]( true || .....); gives true, the remaining segment will not be evaluated.

nsaharia@[Link] JavaScript 13 / 32
Operator Binary Operator

Logical & Comma Operator


b Nullish coalescing (??): Returns its right-hand side operand when its left-hand side operand is
null or undefined, and otherwise returns its left-hand side operand.
- let abc = null ?? 'abc'; [Link](abc); //output: abc
- let bcd = 0 ?? 10; [Link](bcd); //output: 0
b Short-circuit evaluation of logical operators
- Evaluation of Logical/Boolean operations are terminated as soon as the result is certain.
- [Link]( false && ..... ); is short-circuited to give false
- [Link]( true || .....); gives true, the remaining segment will not be evaluated.
b Comma operator (,): Evaluates multiple expressions in a single statement. It combines multiple
expressions into a single expression, and the value of the entire expression is the result of the last
sub-expression. Each sub-expression is evaluated from left to right, and the result of the
rightmost expression is returned. It has the lowest precedence.
- let abc = 1, bcd = 2, cde = 3; [Link](abc, bcd, cde); //output 1 2 3
- let result = (abc++, bcd++, cde++); [Link](abc, bcd, cde); //output 2 3 4
- Check the value of the result variable: [Link](result);
- Another example: let efg = (1 + 2, 3 + 4); [Link](efg);
nsaharia@[Link] JavaScript 13 / 32
Operator Binary Operator

Assignment Operator
b Assignment operators (=): Assign a value to a variable or property. This allows multiple
assignments to be chained in order to assign a single value to multiple variables. Example:
const abc = bcd = cde = 1; [Link](abc); //output: 1
- Arithmetic assignment operators: =, +=, -=, *=, /=, %=, and **=
- Shift assignment operators: <<=, >>=, and >>>=
/ Unsigned right shift assignment >>>= operator performs unsigned right shift on the two
operands and assigns the result to the left operand.
/ What about Unsigned left shift assignment?
- Logical assignment operators: &&=, ||=, and ??=
- Bitwise assignment operators: &=, ^=, and |=
b Nullish Coalescing Assignment operator (??=): Assigns only if a variable is null or undefined
- let abc = 1; abc ??= 2; [Link](abc); //output: 1
- let bcd = null; bcd ??= 2; [Link](bcd); //output: 2
- let cde; cde ??= abc; [Link](cde); //output: 1
b Homework: Check the output for the following expressions
- null || undefined ?? 0;
- (null || undefined) ?? 0;
nsaharia@[Link] JavaScript 14 / 32
Operator Ternary Operator

Ternary Conditional Operator


b A concise way to embed conditions in JavaScript. It is a shorthand for the if-else statement
b Syntax: condition ? trueStatement : falseStatement;
b Example: Compute smallest of two numbers
function smallestOfTwo(n1, n2) {return n1 < n2 ? n1 : n2 ;}
[Link]("The smallest number is: " + smallestOfTwo(8, -2));
b Example: Compute largest of three numbers
function largestOfThree(n1, n2, n3) {
return n1 > n2 ? (n1 > n3 ? n1 : n3) : (n2 > n3 ? n2 : n3); }
[Link](`The largest number is: ${largestOfThree(4, 8, -2)}`);
b Example: Compute largest of three numbers using Arrow function
const largest = (n1, n2, n3) => n1 > n2 ? (n1 > n3 ? n1 : n3) : (n2 > n3 ? n2 : n3);
[Link]("The largest number is: " + largest(4, 8, -2));
b Example: Compute grade against a given score
function computeGrade(scr){
return scr >= 90 ? "A" : scr >= 80 ? "B" : scr >= 70 ? "C" : scr >= 60 ? "D" : "F";}
[Link]("The computed grade is: " + computeGrade(89));
nsaharia@[Link] JavaScript 15 / 32
Operator Precedence of Operator

Precedence and associativity


b Precedence defines the order in which different types of operators are evaluated in an expression.
Operators with higher precedence are evaluated first. Associativity defines the order in which
operators of the same precedence are evaluated when they appear in sequence.

nsaharia@[Link] JavaScript 16 / 32
Operator Precedence of Operator

Precedence and associativity


b Precedence defines the order in which different types of operators are evaluated in an expression.
Operators with higher precedence are evaluated first. Associativity defines the order in which
operators of the same precedence are evaluated when they appear in sequence.
Precedence Associativity Operator
18: Grouping ()
17: Access and call left-to-right ., ?., new a(b)
16: new new //without argument list
15: Postfix operators ++, --
14: Prefix operators ++, --, !, ~, +, , typeof, void, delete, await
13: Exponentiation right-to-left **
12: Multiplicative operators left-to-right * , /, %
11: Additive operators left-to-right + , -
10: Bitwise shift left-to-right <<, >>, >>>
9: Relational operators left-to-right < , <=, >, >=, in, instanceof
8: Equality operators left-to-right ==, !=, ===, !==
7: Bitwise AND left-to-right &
6: Bitwise XOR left-to-right ^
5: Bitwise OR left-to-right |
4: Logical AND left-to-right &&
3: Logical OR, nullish coalescing left-to-right || , ??
2: Assignment and miscellaneous right-to-left =,\=,+=,-=,**= ,*=,/=,%=,<<=,>>=,>>>=,&=
^=, |=, &&=, ||=, ??=,? :, =>, yield, yield*, ...
1: Comma left-to-right ,

nsaharia@[Link] JavaScript 16 / 32
Control Statements If-else statements

Control Statements
b if-else statement
let a = 5; let b = 2, max = 0;
if (condition) {trueBlock;} if (a > b) {max = a;}
else {falseBlock;} else {max = b;}
[Link](max);

nsaharia@[Link] JavaScript 17 / 32
Control Statements If-else statements

Control Statements
b if-else statement
let a = 5; let b = 2, max = 0;
if (condition) {trueBlock;} if (a > b) {max = a;}
else {falseBlock;} else {max = b;}
[Link](max);
b ternary conditional statement

let a = 5; let b = 2;
(condition) ? trueValue :
let max = ( a>b ) ? a : b;
,→ falseValue;
[Link](max);

nsaharia@[Link] JavaScript 17 / 32
Control Statements If-else statements

Control Statements
b if-else statement
let a = 5; let b = 2, max = 0;
if (condition) {trueBlock;} if (a > b) {max = a;}
else {falseBlock;} else {max = b;}
[Link](max);
b ternary conditional statement

let a = 5; let b = 2;
(condition) ? trueValue :
let max = ( a>b ) ? a : b;
,→ falseValue;
[Link](max);
b if-else-if-else ladder
let a = 5, b = 2, max;
if (condition1) {block1;} if (a == b){max = "equal";}
else if (condition2) {block2;} else if (a > b) {max = "largest";}
else {elseBlock;} else {max = "smallest";}
[Link](max);
nsaharia@[Link] JavaScript 17 / 32
Control Statements switch-case

Control Statements-II

b switch statement
let num = 3; let str="";
switch(expression) {
switch(num) {
case value1: {statements; break;}
case 1: {str="One"; break;}
case value2: {statements; break;}
case 2: {str="Two"; break;}
...... ......
case 3: {str="Three";}
default: {statements;}
}
}
[Link](str);

nsaharia@[Link] JavaScript 18 / 32
Control Statements Loop Statements

Loop Statements-I
b while statement
let sum = 0, n = 1;
while (condition) {trueBlock;} while (n <= 10) {sum += n;}
[Link](sum)

nsaharia@[Link] JavaScript 19 / 32
Control Statements Loop Statements

Loop Statements-I
b while statement
let sum = 0, n = 1;
while (condition) {trueBlock;} while (n <= 10) {sum += n;}
[Link](sum)
b do-while statement
let sum = 0, n = 1;
do {trueBlock;} while (condition); do {sum += n;} while (n <= 10);
[Link](sum)

nsaharia@[Link] JavaScript 19 / 32
Control Statements Loop Statements

Loop Statements-I
b while statement
let sum = 0, n = 1;
while (condition) {trueBlock;} while (n <= 10) {sum += n;}
[Link](sum)
b do-while statement
let sum = 0, n = 1;
do {trueBlock;} while (condition); do {sum += n;} while (n <= 10);
[Link](sum)
b for statement
let sum = 0;
for (initialization;
for (let n = 1; n <= 10 ; n += 1){
condition;
sum += n;
post-processing)
}
{trueBlock;}
[Link](sum);

nsaharia@[Link] JavaScript 19 / 32
Control Statements Loop Statements

Loop Statements-II
b for-in statement
let day = ['Sunday', 'Monday', 'Tuesday'];
for (let i in day){[Link](i);}
for (let indx in array)
{trueBlock;}
let str = 'Good day';
for (let i in str){[Link](i);}

nsaharia@[Link] JavaScript 20 / 32
Control Statements Loop Statements

Loop Statements-II
b for-in statement
let day = ['Sunday', 'Monday', 'Tuesday'];
for (let i in day){[Link](i);}
for (let indx in array)
{trueBlock;}
let str = 'Good day';
for (let i in str){[Link](i);}

Append this code segment with the previous day[7] = 'Saturday';


statements and check the output for (let i in day){
[Link](i + " = " + day[i]);}

nsaharia@[Link] JavaScript 20 / 32
Control Statements Loop Statements

Loop Statements-II
b for-in statement
let day = ['Sunday', 'Monday', 'Tuesday'];
for (let i in day){[Link](i);}
for (let indx in array)
{trueBlock;}
let str = 'Good day';
for (let i in str){[Link](i);}

Append this code segment with the previous day[7] = 'Saturday';


statements and check the output for (let i in day){
[Link](i + " = " + day[i]);}
b for-of statement
let days = ['Sunday', 'Monday', 'Tuesday'];
for (let i of days){[Link](i);}
for (let indx of iterables)
{trueBlock;}
let str = 'Good day';
for (let i of str){[Link](i);}

nsaharia@[Link] JavaScript 20 / 32
Handling errors in JavaScript

Exception

b Exception → Error or other special condition, which can be thrown by the JavaScript interpreter
when
- a runtime error occurs
- it is thrown in the program explicitly using throw statement

nsaharia@[Link] JavaScript 21 / 32
Handling errors in JavaScript

Exception

b Exception → Error or other special condition, which can be thrown by the JavaScript interpreter
when
- a runtime error occurs
- it is thrown in the program explicitly using throw statement

b The syntax of the throw statement throw exception;


b The exception can be value of any type: throw 10;, throw true;, or throw "Error";

nsaharia@[Link] JavaScript 21 / 32
Handling errors in JavaScript

Exception

b Exception → Error or other special condition, which can be thrown by the JavaScript interpreter
when
- a runtime error occurs
- it is thrown in the program explicitly using throw statement

b The syntax of the throw statement throw exception;


b The exception can be value of any type: throw 10;, throw true;, or throw "Error";

b When an exception is thrown, interpreter stops the program execution immediately and jumps to the
nearest exception handler. Exceptions handlers are defined by catch clause of try-catch statement.
b If an exception is thrown and no exception handler is found, the exception is treated as an error.

nsaharia@[Link] JavaScript 21 / 32
Handling errors in JavaScript Error Types

Error Types

b There are 7 types of JavaScript errors


- Syntax error: Raises when tokens or token order that does not conform to the syntax of the
language while parsing code

- Reference error: Raises when non-existent variables referenced somewhere

- Type error: Raises, when an operation could not be performed.

- Range error: Raises, when a value of a variable is not in the range of allowed values

- URI error: Raises, when a global URI handling function was used in a wrong way

- Evaluation error: Raises for an invalid global eval() function

- Internal error: Raises, when an error occurs internally in the JavaScript engine.

nsaharia@[Link] JavaScript 22 / 32
Handling errors in JavaScript Error Types

SyntaxError

b Raises when tokens or token order that does not conform to the syntax of the language while parsing
code

try {
let a = a+ ;
}
catch (e) {
[Link]([Link] + ": "+ [Link]);
}

Output: SyntaxError: Unexpected token ';'

Replace ‘let a = a+ ;’ with ‘let a = a++; in the above example and check the generated output.

nsaharia@[Link] JavaScript 23 / 32
Handling errors in JavaScript Error Types

ReferenceError

b Raises when non-existent variables referenced somewhere

try{
var a = a + c;
}
catch(e){
[Link]([Link] +"->"+ [Link]);
}

Output: ReferenceError -> c is not


,→ defined

nsaharia@[Link] JavaScript 24 / 32
Handling errors in JavaScript Error Types

ReferenceError

b Raises when non-existent variables referenced somewhere

try{ try{
var a = a + c; let a = a + c;
} }
catch(e){ catch(e){
[Link]([Link] +"->"+ [Link]); [Link]([Link] +"->"+ [Link]);
} }

Output: ReferenceError -> c is not Output: ReferenceError -> Cannot access


,→ defined ,→ 'a' before initialization

nsaharia@[Link] JavaScript 24 / 32
Handling errors in JavaScript Error Types

TypeError
b Raises, when an operation could not be performed
b Situations when TypeError may occur
- Attempting to modify a value that cannot be changed
- Attempting to use a value in an inappropriate way
- Incompatible argument passed to a function

try{
let e = new true;
}
catch(e){
[Link]([Link] +" -> "+ [Link]);
}
Output: TypeError -> true is not a
,→ constructor

nsaharia@[Link] JavaScript 25 / 32
Handling errors in JavaScript Error Types

TypeError
b Raises, when an operation could not be performed
b Situations when TypeError may occur
- Attempting to modify a value that cannot be changed
- Attempting to use a value in an inappropriate way
- Incompatible argument passed to a function

const pi = 3.14;
try{
try{
let e = new true;
pi = 3.1459;
}
}
catch(e){
catch(e){
[Link]([Link] +" -> "+ [Link]);
[Link]([Link] +"->"+ [Link]);
}
}
Output: TypeError -> true is not a
Output: TypeError -> Assignment to
,→ constructor
,→ constant variable.
Replace true with abc in the above example and check the output.
nsaharia@[Link] JavaScript 25 / 32
Handling errors in JavaScript Error Types

RangeError
b Raises, when a value of a variable is not in the range of allowed values
b Situations when RangeError may occur
- Passing a value that is not one of the allowed values
- Attempting to create an array of an illegal length with constructor
- Passing bad values to the numeric methods

try{
let arr = new Array(-1);
}
catch(e){
[Link]([Link] +"->"+ [Link]);
}

Output: RangeError -> Invalid array


,→ length

nsaharia@[Link] JavaScript 26 / 32
Handling errors in JavaScript Error Types

RangeError
b Raises, when a value of a variable is not in the range of allowed values
b Situations when RangeError may occur
- Passing a value that is not one of the allowed values
- Attempting to create an array of an illegal length with constructor
- Passing bad values to the numeric methods

try{
try{
let abc = BigInt(NaN);
let arr = new Array(-1);
}
}
catch(e){
catch(e){
[Link]([Link] +"->"+ [Link]);
[Link]([Link] +"->"+ [Link]);
}
}
Output: RangeError -> The number NaN
Output: RangeError -> Invalid array
,→ cannot be converted to a BigInt
,→ length
,→ because it is not an integer
nsaharia@[Link] JavaScript 26 / 32
Handling errors in JavaScript Error Types

URIError

b Raises, when a global URI handling function was used in a wrong way
- An argument passed either to decodeURI, encodeURI, encodeURIComponent, or
decodeURIComponent
try {
decodeURIComponent("%");
decodeURI("%")
}
catch (e) {
[Link]([Link] + ": "+ [Link] + " at line number "+ [Link]);
}

Output: URIError: URI malformed at line number .....

nsaharia@[Link] JavaScript 27 / 32
Handling errors in JavaScript Error Types

EvalError

b eval() function evaluates JavaScript code represented as a string and returns its completion value
b Raises for an invalid global eval() function.
b Current interpreters are not throwing EvalError

try{
throw new EvalError("Eval error");
}
catch(e){
[Link]([Link] +": "+ [Link]);
}

Output: EvalError: Eval error

nsaharia@[Link] JavaScript 28 / 32
Handling errors in JavaScript Error Types

EvalError

b eval() function evaluates JavaScript code represented as a string and returns its completion value
b Raises for an invalid global eval() function.
b Current interpreters are not throwing EvalError

try{
try{
let e = new eval();
throw new EvalError("Eval error");
}
}
catch(e){
catch(e){
[Link]([Link] +": "+ [Link]);
[Link]([Link] +": "+ [Link]);
}
}
Output: TypeError: eval is not a
Output: EvalError: Eval error
,→ constructor

nsaharia@[Link] JavaScript 28 / 32
Handling errors in JavaScript Error Types

InternalError
b Raises, when an error occurs internally in the JavaScript engine.
b Situations when InternalError may occur
- too many switch cases
- too many parentheses in regular expression
- array initializer too large
- too much recursion
function factorial(a) { if (a > 100) return; else return a * factorial(a-1)}

try {
[Link](factorial(5));
}
catch (e) {
[Link]([Link] + ": "+ [Link] + " at line number "+ [Link]);
}
Output: RangeError: Maximum call stack size exceeded at line number .....
InternalError in Firefox; RangeError in Chrome and Safari.
nsaharia@[Link] JavaScript 29 / 32
Handling errors in JavaScript Exception handling

Genaral Syntax
try {
let a = a++;
} catch (error) {
[Link]("[" + [Link]+"] " +
[Link] + ": " +
[Link] + " at line no.: " +
[Link] + ", column no.: "+
[Link] + ", and stack: [" +
[Link] + "] ");
}
finally {
[Link]("Error is due to Reference");

Output: [...] ReferenceError: Cannot access 'a' before initialization at line no.:
,→ ..., column no.: ..., and stack: [....]
Error is due to Reference
nsaharia@[Link] JavaScript 30 / 32
Handling errors in JavaScript Exception handling

Exception handling-I

b Exception handling in JavaScript is almost the same as in Java

b Throw expression creates and throws an exception

b The expression is the value of the exception, and can be of any type (often, it’s a literal String)
try { statements to try }
catch (e) {exception-handling statements}
finally {code that is always executed}

nsaharia@[Link] JavaScript 31 / 32
Handling errors in JavaScript Try-catch ladder with finally

Exception handling-II

try {statements to try}


catch (e if test1) {exception-handling for the case that test1 is true}
catch (e if test2) {exception-handling for the case when test2 is true}
catch (e) {exception-handling for when both test1 and test2 are false}
} finally {code that is always executed}

Typically, the test would be something like e == InvalidNameException

nsaharia@[Link] JavaScript 32 / 32

You might also like