JavaScript Part II
JavaScript Part II
JavaScript
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
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
nsaharia@[Link] JavaScript 5 / 32
Operator Unary Operator
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
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
nsaharia@[Link] JavaScript 6 / 32
Operator Unary Operator
Unary Operator - IV
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
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
nsaharia@[Link] JavaScript 9 / 32
Operator Binary Operator
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
nsaharia@[Link] JavaScript 11 / 32
Operator Binary Operator
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
nsaharia@[Link] JavaScript 13 / 32
Operator Binary Operator
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
nsaharia@[Link] JavaScript 16 / 32
Operator Precedence of Operator
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);}
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);}
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
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 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
- 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
- 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]);
}
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
try{
var a = a + c;
}
catch(e){
[Link]([Link] +"->"+ [Link]);
}
nsaharia@[Link] JavaScript 24 / 32
Handling errors in JavaScript Error Types
ReferenceError
try{ try{
var a = a + c; let a = a + c;
} }
catch(e){ catch(e){
[Link]([Link] +"->"+ [Link]); [Link]([Link] +"->"+ [Link]);
} }
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]);
}
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]);
}
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]);
}
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 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
nsaharia@[Link] JavaScript 32 / 32