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

JS

The document provides an overview of JavaScript, including its history, features, and unique aspects such as variable types, operators, and type conversions. It explains the differences between JavaScript and other languages like Java, CoffeeScript, and TypeScript, as well as the structure of JavaScript code and common practices for using it in HTML. Additionally, it addresses frequently asked questions and interview questions related to JavaScript concepts and functionalities.

Uploaded by

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

JS

The document provides an overview of JavaScript, including its history, features, and unique aspects such as variable types, operators, and type conversions. It explains the differences between JavaScript and other languages like Java, CoffeeScript, and TypeScript, as well as the structure of JavaScript code and common practices for using it in HTML. Additionally, it addresses frequently asked questions and interview questions related to JavaScript concepts and functionalities.

Uploaded by

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

 Promise chaining  server-sent events

 Callback hell  web worker or service worker in


 Temporal dead zone javascript
 prototype chain  Debouncing and Throttling
 Object.create() method
 Call, Apply, and Bind
 currying function
 Execution context, execution stack,
variable object, scope chain
 priority of execution of callback,
promise, setTimeout,
process.nextTick
 Factory function and generator
function
 ways to clone (Shallow and deep
copy of object) an object
 make an object immutable? (seal
and freeze methods)
 Event and event flow, event
bubbling and event capturing
 Event delegation 1
JavaScript

2
An Introduction to JavaScript
 JavaScript was initially created to “make web pages alive”.
 The programs in this language are called scripts. They can be
written right in a web page’s HTML and run automatically as the
page loads.

Why is it called JavaScript?


 When JavaScript was created, it initially had another name:
“LiveScript”. But Java was very popular at that time, so it was
decided that positioning a new language as a “younger brother” of
Java would help.
 But as it evolved, JavaScript became a fully independent language
with its own specification called ECMAScript, and now it has no
relation to Java at all.

3
What makes JavaScript unique?
 Full integration with HTML/CSS.
 Simple things are done simply.
 Supported by all major browsers and enabled by default.

4
Languages “over” JavaScript
 The syntax of JavaScript does not suit everyone’s needs. Different
people want different features.
 The syntax of JavaScript does not suit everyone’s needs. Different
people want different features.
 CoffeeScript is “syntactic sugar” for JavaScript. It introduces shorter
syntax, allowing us to write clearer and more precise code. Usually,
Ruby devs like it.
 TypeScript is concentrated on adding “strict data typing” to simplify
the development and support of complex systems. It is developed by
Microsoft.
 Dart is a standalone language that has its own engine that runs in
non-browser environments (like mobile apps), but also can be
transpiled to JavaScript. Developed by Google.
 Kotlin is a modern, concise and safe programming language that can
target the browser or Node.
5
File Extension
 .js

Versions of JavaScript
 The Original JavaScript ES1 ES2 ES3 (1997-1999)
 The First Main Revision ES5 (2009)
 The Second Revision ES6 (2015)

6
Commonly Asked Questions
1. How do I get JavaScript?
Answer : You don't have to get or download JavaScript.

2. Where can I download JavaScript?


Answer : JavaScript is already running in your browser on your
computer, on your tablet, and on your smart-phone.

3. Is JavaScript Free?
Answer : JavaScript is free to use for everyone.

7
Some examples of what JavaScript can do.
 JavaScript Can Change HTML Content
 JavaScript Can Change HTML Attribute Values
 JavaScript Can Change HTML Styles (CSS)
 JavaScript Can Hide HTML Elements
 JavaScript Can Show HTML Elements

8
The “script” tag
 In HTML, JavaScript code is inserted in script tag

<script>
…… JavaScript code here …
</script>

JavaScript in <head> or <body>


 JavaScript programs can be inserted almost anywhere into an HTML
document using the <script> tag but the common practice is to put it
inside head or body tag.
 You can place any number of scripts in an HTML document.

9
External JavaScript
 Scripts can also be placed in external files.
 External scripts are practical when the same code is used in many
different web pages.
 To use an external script, put the name of the script file in the src
(source) attribute of a <script> tag
Example
<script src="myScript.js"></script>

 External scripts cannot contain <script> tags.


 If we have a lot of JavaScript code, we can put it into a separate file.
 To add several script files to one page - use several script tags
Example
 <script src="myScript1.js"></script>
<script src="myScript2.js"></script>
10
Advantages of External JavaScript
 It separates HTML and code
 It makes HTML and JavaScript easier to read and maintain

 The benefit of a separate file is that the browser will download it


and store it in its cache.
 Other pages that reference the same script will take it from the
cache instead of downloading it, so the file is actually downloaded
only once.
 That reduces traffic and makes pages faster.
 Cached JavaScript files can speed up page loads

11
Interview Questions…
1. What is JavaScript? What is it used for?
2. Does JavaScript has any relation with java?
3. Why don't we need to install JavaScript?
4. What extension do we use to create a JavaScript file?
5. What does JavaScript can do?
6. What are the different ways to insert JavaScript code in html
file?
7. What is the difference between internal JavaScript and
external JavaScript?
8. How can we write internal JavaScript?
9. How can we write external JavaScript?
10. What are the advantages of external JavaScript?
12
Code structure
Statements
 Statements are syntax constructs and commands that perform
actions.
 We can have as many statements in our code as we want.
 Statements can be separated with a semicolon.

Comments
 One-line comments start with two forward slash characters.
 Multiline comments start with a forward slash and an asterisk (/*)
and end with an asterisk and a forward slash (*/)
 Nested comments are not supported!

13
Code structure
Semicolons
 JavaScript interprets the line break as an “implicit” semicolon.
 In most cases, a newline implies a semicolon. But “in most cases” it doesn’t.
 But there are situations where JavaScript “fails” to assume a semicolon
where it is really needed.
Code 1
alert("Hello");
[1, 2].forEach(alert);
Code 2
alert("Hello")
[1, 2].forEach(alert);

 It is recommended to put semicolons between statements even if they are


separated by newlines.

14
JavaScript Variables (Variables are used to store information or value.)

Let
 Example
let message;

 Now, we can put some data into it by using the assignment operator “=”
 Example
let message;
message = 'Hello‘;

 The string is now saved into the memory area associated with the
variable. We can access it using the variable name:
 Example
alert(message);

15
JavaScript Variables

Let
 Used for block scope variable.
 We can combine the variable declaration and assignment into a single
line
 Example
let message = 'Hello!';
alert(message);

 We can also declare multiple variables in one line


 Example
let user = 'John', age = 25, message = 'Hello';

16
JavaScript Variables

Var

 In older scripts, you may also find another keyword var instead of let
 var keyword is almost the same as let. It also declares a variable, but in a
slightly different, “old-school” way.

 When the value is changed, the old data is removed from the variable:

17
JavaScript Variables
Const
 To declare a constant (unchanging) variable, use const instead of let/var.
 Variables declared using const are called “constants”. They cannot be
reassigned. An attempt to do so would cause an error
 When a programmer is sure that a variable will never change, they can
declare it with const to guarantee and clearly communicate that fact to
everyone.
 Example
const myBirthday = '18.04.1982';

 Uppercase constants
 There is a widespread practice to use constants as aliases for
difficult-to-remember values that are known prior to execution.
 Such constants are named using capital letters and underscores.
 Example
const COLOR_RED = "#F00"; 18
19
20
JavaScript Variables

Note : Declaring twice triggers an error

Variable naming
 There are two limitations on variable names in JavaScript
1. The name must contain only letters, digits, or the symbols
2. The first character must not be a digit.

Points to remember
 Case matters
 Non-Latin letters are allowed, but not recommended.
 Reserved names (predefined keywords)

21
JavaScript Variables Block Scope
 Global Scope
 Variables declared with the var keyword can NOT have block scope.
 Variables declared inside a { } block can be accessed from outside
the block.
 Example
{ var x = 2; }
// x CAN be used here
 Function Scope
 ES6 introduced two important new JavaScript keywords let & const.
 These two keywords provide Block Scope in JavaScript.
 Variables declared inside a { } block cannot be accessed from outside
the block
 Example
{ let x = 2; }
// x can NOT be used here
22
JavaScript Data types
 Number
let n = 123;
 BigInt (rarely needed)
 It is supported in Firefox/Chrome/Edge/Safari, but not in IE.
 Example
const bigInt = 1234567890123456789012345678901234567890n;
 String
 A string in JavaScript must be surrounded by quotes.
 In JavaScript, there are 3 types of quotes.
1. Double quotes
let str1 = "Hello";
2. Single quotes
let str2 = 'Single quotes are ok too';
3. Backticks
let phrase = `can embed another ${str}`;
23
JavaScript Data types
 Boolean (logical type)
let variable = true;

 The “null” value


 It is not a “reference to a non-existing object” or a “null pointer” like in
some other languages.
 It’s just a special value which represents “nothing”, “empty” or “value
unknown”.
 Example
let age = null;

 The “undefined” value


 It means “value is not assigned”.
 Example
let age;
24
JavaScript Data types

 The typeof operator

 This operator returns the type of the operand.


 It’s useful when we want to process values of different types differently
or just want to do a quick check.

 Example
typeof(x);
typeof x

25
Interview Questions…
1. What is the difference between let, var and const?
2. What is the difference between let and var?
3. What is the difference between global scope and
functional scope?
4. Name the datatypes used in JavaScript?
5. What are Backticks?
6. What are template literals? What are they used for?
7. What is the difference between datatype null and
undefined in JavaScript?
8. what method/operator can we use in JavaScript to find
out the datatype of a variable?
9. What is typeof operator? What does it do? 26
JavaScript Operators

 Arithmetic Operators

 These Operators are used to perform arithmetic on numbers


 Addition (+)
 Multiplication (*)
 Subtraction (-)
 Division (/)
 Modulus (Division Remainder) (%)
 Increment (++)
 Decrement (--)
 Exponentiation (**)

27
JavaScript Operators

 Assignment Operators

 The Assignment Operator (=) assigns a value to a variable.


 The Addition Assignment Operator (+=) adds a value to a variable.
 Example
let x = 10;
x += 5;

 (-=), (*=), (/=),


 The (+) operator can also be used to add (concatenate) strings.
 Example
let text1 = "John“ ;
let text2 = "Doe";
let text3 = text1 + " " + text2;
28
JavaScript Operators

 Comparison Operators

 Equal to (==)
 Equal value and equal type (===)
 Not equal (!=)
 Not equal value or not equal type (!==)
 Greater than (>)
 Less than (<)
 Greater than or equal to (>=)
 Less than or equal to (<=)
 Ternary operator (?)

29
JavaScript Operators
 Logical Operators

 logical and (&&)


 logical or (||)
 logical not (!)

 Type Operators
 Instanceof
 Returns true if an object is an instance of an object type
const cars = ["Saab", "Volvo", "BMW"];
Console.log(cars instanceof Array)
 typeof
 Returns the type of a variable
const cars = ["Saab", "Volvo", "BMW"];
Console.log(typeof cars)
30
Interview Questions…
1. List the types of operators used in JavaScript?
2. What does modulus (%) operator do?
3. What does increment (++) operator do?
4. What does decrement (--) operator do?
5. What does addition assignment (+=) operator do?
6. What is the difference between == and ===?
7. What is the difference between != and !==?
8. What is ternary operator? What is it used for in JavaScript?
9. List out logical operators used in JavaScript?
10. What is the difference between logical and (&&) and logical or (||)?
11. What is instanceof operator used for?
31
JavaScript Type Conversions
 String Conversion
 String conversion happens when we need the string form of a value.
 Example
Let num = 1
Let str = String(num)

 Numeric Conversion
 Numeric conversion in mathematical functions and expressions
happens automatically.
 We can use this conversion function to explicitly convert a value to
number.
 String must contain number only to convert it to a number.
 Example
let str = "123";
let num = Number(str)
32
JavaScript Type Conversions

 Boolean Conversion
 Boolean conversion is the simplest one.
 The conversion rule
 Values that are intuitively “empty”, like 0, an empty
string, null, undefined and NaN become false
 Other values become true

 Example
Let num = 1;
Boolean(num) //returns true

Let str = “”;


Boolean(str) //returns false

33
Interview Questions…
1. What do u mean by type conversion?
2. What method do u use to convert a variable of any datatype in number?
3. What method do u use to convert a variable of any datatype in string?
4. What method do u use to convert a variable of any datatype in Boolean?
5. What will be the output of console.log(Number("1234x"))?
6. What will be the output of console.log(Boolean("1234x"))?
7. What will be the output of console.log(Boolean(123))?
8. What will be the output of console.log(Boolean(undefined))?
9. What will be the output of console.log(Boolean(null))?
10. What will be the output of console.log(Boolean(""))?

34
JavaScript if, else, and else if
 If Statement
 Use this statement to specify a block of JavaScript code to be
executed if a condition is true.
 Syntax
if (condition) {
// block of code to be executed if the condition is true
}
 Else Statement
 Use this statement to specify a block of code to be executed if the
condition is false.
 Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
} 35
JavaScript if, else, and else if

 Else if Statement

 Use this statement to specify a new condition if the first condition is


false.
 Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and
condition2 is true
} else {
// block of code to be executed if the condition1 is false and
condition2 is false
}
36
Conditional (Ternary) Operator Statement
 JavaScript also contains a conditional operator that assigns a value to a
variable based on some condition.
Syntax
condition ? Code block 1 : Code block 2 ;
let Variable = condition ? value1 : value2 ;

Example
using if Else statement
let a;
if (age > 18) { a = true; }
else { a = false; }

using ternary operator statement


let a;
a = age > 18 ? true : false;
37
JavaScript Switch Statement
 This statement is used to perform different actions based on different
conditions.
 Use the switch statement to select one of many code blocks to be executed.
 Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

Note : The default keyword specifies the code to run if there is no case match:38
JavaScript Switch Statement
 This is how it works
• The switch expression is evaluated once.
• The value of the expression is compared with the values of each case.
• If there is a match, the associated block of code is executed.
• If there is no match, the default code block is executed.

 The break Keyword


 When JavaScript reaches a break keyword, it breaks out of the
switch block.
 This will stop the execution inside the switch block.
 It is not necessary to break the last case in a switch block. The block
breaks (ends) there anyway.

Note: If you omit the break statement, the next case will be executed even if
the evaluation does not match the case.
39
JavaScript Switch Statement
 Common Code Blocks
 Sometimes you will want different switch cases to use the same
code.
 Example
switch (new Date().getDay()) {
case 4:
case 5:
text = "Soon it is Weekend";
break;
case 0:
case 6:
text = "It is Weekend";
break;
default:
text = "Looking forward to the Weekend";
} 40
JavaScript Loops (The While Loop)
 The while loop loops through a block of code as long as a specified
condition is true.
 Syntax
while (condition) {
// code block to be executed
// increment
}

 A single execution of the loop body is called an iteration.


 If you forget to increase the variable used in the condition, the loop will
never end. This will crash your browser.
 If (i++) increment was missing from the example above, the loop would
repeat (in theory) forever. In practice, the browser provides ways to stop
such loops, and in server-side JavaScript, we can kill the process.

41
JavaScript Loops (The Do-While Loop)
 The Do-while loop is a variant of the while loop. This loop will execute the
code block once, before checking if the condition is true, then it will repeat
the loop as long as the condition is true.
 Syntax
do {
// code block to be executed
// increment
}
while (condition);

 The loop will always be executed at least once, even if the condition is false,
because the code block is executed before the condition is tested.
 Do not forget to increase the variable used in the condition, otherwise the
loop will never end!
 This form of syntax should only be used when you want the body of the loop
to execute at least once regardless of the condition being true or false. 42
Interview Questions…
1. What is the difference between if statement, if-else statement and nested
if-else statement? Explain with syntax and example.
2. What is ternary operator? What is it used for?
3. Explain switch statement with syntax.
4. What does default block do in switch statement?
5. What does break keyword do in switch statements?
6. What are common code blocks in switch statements? How does they
work?
7. What is while loop in JavaScript? Explain with syntax and example.
8. What is do-while loop in JavaScript? Explain with syntax and example.
9. What is the difference between while and do-while loop?
43
JavaScript Loops (The For Loop)
 The For loop is more complex, but it’s also the most commonly used loop.
 Syntax
for (begin; condition; step) {
// ... loop body ...
}
 Example
for (let i = 0; i < 3; i++) {
alert(i);
// shows 0, then 1, then 2
}

begin let i = 0 Executes once upon entering the loop.


condition i<3 Checked before every loop iteration. If false, the loop stops.
body Console.log(i) Runs again and again while the condition is true.
step i++ Executes after the body on each iteration.
44
JavaScript Loops (The For Loop)
 The general loop algorithm works like this
Run begin
→ (if condition → run body and run step)
→ (if condition → run body and run step)
→ (if condition → run body and run step)
→ ...

 You can initiate many values in begin (separated by comma)


 Example
 for (let i = 0, len = cars.length, text = ""; i < len; i++) {
text += cars[i] + "<br>";
}

 If condition returns true, the loop will start over again. If it returns false, the
loop will end.
45
JavaScript Loops (The For-Of Loop)
 The For Of statement loops through the values of an iterable object.
 It lets you loop over iterable data structures such as Arrays, Strings, Maps,
NodeLists, and more.
 Syntax
for (variable of iterable) {
// code block to be executed
}
variable - For every iteration the value of the next property is assigned
to the variable. Variable can be declared with let, const, var
iterable - An object that has iterable properties.
 Example
let text = “JavaScript";
for (let x of text) {
console.log(x)
}
46
JavaScript Loops (The For-In Loop)
 For-In Loop over Object
 The for-in statement loops through the properties of an Object
 Syntax
for (key in object) {
// code block to be executed
}
 Example
const person = { fname: "John", lname: "Doe", age: 25 };
for (let x in person) {
console.log(x); // Prints ' fname ', ' lname ', ' age '
console.log(person[x]); // Access the values: John, Doe, 25
}
 Example Explained
• The for in loop iterates over a person object
• Each iteration returns a key (x)
• The key is used to access the value of the key
• The value of the key is person[x]
47
JavaScript Loops (The For-In Loop)
 For-In Loop over Arrays
 The for-in statement can also loop over the properties of an Array
 Syntax
for (variable in array) {
// code to be executed
}
 Example
const numbers = [45, 4, 9, 16, 25];
let txt = "";
for (let x in numbers) {
txt += numbers[x];
console.log(txt);
}
 Do not use for in over an Array if the index order is important.
 It is better to use a for loop, a for of loop, or Array.forEach() when
the order is important. 48
Difference between For-Of and For-In loop
 Iterated values
• for...in is used to examine the properties of an object, including those
inherited from its parent object. It provides the property keys, allowing you
to access the corresponding values if necessary. However, the order of
iteration may not match the order in which the properties were defined in
the object.
• for...of allows you to go through the elements of an iterable one at a time.
It gives you the actual values directly, without concerning yourself with
properties or keys. The order of iteration typically follows the order in
which the elements were added for arrays, and for other iterables, it
follows the defined order.

 Errors
• If you attempt to use for...of with an object that is not iterable, it will
throw an error. On the other hand, for...in can still be used to loop over the
properties of any object, regardless of whether it is iterable or not.
49
Difference between For-Of and For-In loop
 Performance
• for...in can be slower than for...of due to the extra steps involved in
property enumeration. However, the impact on performance is generally
negligible unless you are working with a large number of properties.

 Nesting
• for...in provides a way to iterate over nested objects or access properties in
a hierarchical structure. It allows you to traverse through the levels of
nested properties by using nested for...in loops. On the other hand, for...of
is not designed to handle such complex structures and is primarily suited
for straightforward iteration over the values of an iterable like arrays,
strings, maps, or sets. If you need to work with nested objects or traverse a
hierarchy, for...in is the appropriate choice.

50
JavaScript Loops (The forEach Loop)
 The forEach method calls a function (a callback function) once for each
array element.
 Syntax
array.forEach((value, index) => {
console.log(index, "-->", info);
});
 Example
const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);
function myFunction(value, index, array) {
txt += value;
}
Note that the function takes 3 arguments:
• The item value
• The item index
• The array itself
51
JavaScript Loops (The map method)
 This method is one of the most useful and often used.

 Syntax
array.map((value, index) => {
console.log(index, "-->", info);
});

 Example
person = [1,2,3,4,5,6]
person.map((info, i) => {
console.log(i, "-->", info);
});

52
Difference between map and forEach method
 The returning value
 Foreach() method returns undefined and map() returns a new array
with the transformed elements. Even if they do the same job, the
returning value remains different.

 Ability to chain other methods


 You can attach reduce(), sort(), filter() and so on after performing a
map() method on array. That's something you can't do with
forEach() because it returns undefined

 Performance Speed

 Mutability

53
Interview Questions…
1. How does for loop works? Explain with example and syntax.
2. What is for-of loop? Explain with example and syntax
3. What is for-in loop? Explain with example and syntax
4. What is the difference between for-of and for-in loops?
5. What is forEach method? Explain with syntax and example.
6. What is map method? Explain with syntax and example.
7. What is the difference between map and forEach?

54
JavaScript Functions
 Function Declaration
 Function keyword goes first, then goes the name of the function,
then a list of parameters between the parentheses
 Syntax
function name(parameter1, parameter2, ... parameterN) {
// body
}
 Local variables
 A variable declared inside a function is only visible inside that
function.
 Outer variables
 The function has full access to the outer variable. It can modify it as
well.
 If a same-named variable is declared inside the function then
it shadows the outer one.
55
JavaScript Functions
 Parameters
 We can pass arbitrary data to functions using parameters.
 When a value is passed as a function parameter, it’s also called
an argument.
 A parameter is the variable listed inside the parentheses in the
function declaration (it’s a declaration time term).
 An argument is the value that is passed to the function when it is
called (it’s a call time term).
 Default values
 If a function is called, but an argument is not provided, then
the corresponding value becomes undefined.

56
JavaScript Functions
 Parameters
 Default Parameter Values
function myFunction(x, y = 10) {
// y is 10 if not passed or undefined
return x + y;
}
myFunction(5); // will return 15
 Function Rest Parameter
The rest parameter (...) allows a function to treat an indefinite
number of arguments as an array.
function fun(...input) {
let sum = 0;
for (let i of input) {
sum += i;
}
return sum;
}
console.log(fun(1, 2, 3)); //6
console.log(fun(1, 2, 3, 4, 5)); //15 57
JavaScript Functions
 Parameters
 Function Rest Parameter
// rest with function and other arguments
function fun(a, b, ...c) {
console.log(`${a} ${b}`); //Mukul Latiyan
console.log(c); //[ 'Lionel', 'Messi', 'Barcelona' ]
console.log(c[0]); //Lionel
console.log(c.length); //3
console.log(c.indexOf('Lionel')); //0
}
fun('Mukul', 'Latiyan', 'Lionel', 'Messi', 'Barcelona');

58
JavaScript Functions
 Returning a value
 A function can return a value back into the calling code as the result.
 Example
function sum(a, b) {
return a + b;
}
 There may be many occurrences of return in a single function.
 Example
function checkAge(age) {
if (age >= 18) { return true; }
else { return false; }
}
 A function with an empty return or without it returns undefined
 Never add a newline between return and value because JavaScript
assumes a semicolon after
59
JavaScript Arrow Function
 Arrow functions were introduced in ES6.
 Arrow functions allow us to write shorter function syntax

 Before Arrow
Function hello(parameters) {
return "Hello World!";
}
 With Arrow Function
Const hello = () => {
return "Hello World!";
}

 It gets shorter! If the function has only one statement, and the statement
returns a value, you can remove the brackets and the return statement.
 Note: This works only if the function has only one statement.
60
JavaScript Callbacks/ Callback Functions
 A callback is a function passed as an argument to another function
 This technique allows a function to call another function
 A callback function can run after another function has finished

 Function Sequence

• JavaScript functions are executed in the sequence they are called.


• Not in the sequence they are defined.

function myFirst() { console.log("Hello"); }


function mySecond() { console.log("Goodbye"); }

myFirst();
mySecond();

61
Callback Hell
• JavaScript, a single-threaded language, relies on callbacks for handling asynchronous
tasks. Callbacks execute code once an operation finishes. But as the code complexity
increases, the risk of callback hell emerges.

• A callback is a function that is passed as an argument to another function that executes the
callback based on the result. They are basically functions that are executed only after a
result is produced. Callbacks are an important part of asynchronous JavaScript.

• Callback Hell is essentially nested callbacks stacked below one another forming a pyramid
structure. Every callback depends/waits for the previous callback, thereby making a
pyramid structure that affects the readability and maintainability of the code.

62
Callback Hell
Here's a simple example to illustrate callback hell:

asyncOperation1(param1, (result1) => {


// Callback 1
asyncOperation2(result1, (result2) => {
// Callback 2
asyncOperation3(result2, (result3) => {
// Callback 3
// Nested asynchronous operations continue...
});
});
});

• asyncOperation1 is called, and when it completes, it executes Callback 1.


• Inside Callback 1, asyncOperation2 is called, and when it completes, it executes Callback 2.
• Inside Callback 2, asyncOperation3 is called, and when it completes, it executes Callback 3.
• This nesting can continue, creating a pyramid-like structure of callbacks, which becomes
increasingly difficult to manage as the codebase grows.
63
Callback Hell

Solutions to callback hell

There are four solutions to callback hell:

1. Write comments
2. Split functions into smaller functions
3. Using Promises
4. Using Async/await

64
JavaScript Callbacks/ Callback Functions
 Sequence Control

• Sometimes you would like to have better control over when to


execute a function.
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}
function myCalculator(num1, num2) {
let sum = num1 + num2;
return sum;
}

let result = myCalculator(5, 5);


myDisplayer(result);

• The problem with examples above, is that you have to call two
functions to display the result.
65
JavaScript Callbacks/ Callback Functions
 JavaScript Callbacks
 A callback is a function passed as an argument to another function.
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}

function myCalculator(num1, num2, myCallback) {


let sum = num1 + num2;
myCallback(sum);
}

myCalculator(5, 5, myDisplayer);

• In the example above, myDisplayer is a called a callback function.


• It is passed to myCalculator() as an argument.

• When you pass a function as an argument, remember not to use


parenthesis. 66
Hoisting in JavaScript
 Hoisting is a concept or behavior in JavaScript where the declaration of a
function, variable, or class goes to the top of the scope they were defined
in.

 JavaScript Declarations are Hoisted


• In JavaScript, a variable can be declared after it has been used.
• In other words; a variable can be used before it has been declared.

 JavaScript Initializations are Not Hoisted


• JavaScript only hoists declarations, not initializations.

 Declare Your Variables At the Top !


• If a developer doesn't understand hoisting, programs may contain bugs (errors).
• To avoid bugs, always declare all variables at the beginning of every scope.
• Since this is how JavaScript interprets the code, it is always a good rule.

67
Hoisting in JavaScript
 Function Hoisting
Code 1:
function printHello() {
console.log("hello")
}
printHello();

• Here, we declare printHello, and we execute the function just after the line it was
declared. No errors; everything works!

Code 2
printHello()
function printHello() {
console.log("hello")
}

• Here, we execute printHello before the line the function was declared. And
everything still works without errors. What happened here? Hoisting.
68
Hoisting in JavaScript
 Function Hoisting

• Before the interpreter executes the whole code, it first hoists (raises, or lifts) the
declared function to the top of the scope it is defined in.
• In this case, printHello is defined in the global scope, so the function is hoisted to
the top of the global scope.
• Through hoisting, the function (including the logic) becomes accessible even
before the line it was declared in the code.

• Arrow functions are not hoisted as they are also function expressions where the
function is assigned as a value to the variable.

69
Hoisting in JavaScript
 Variable Hoisting
• You can declare variables in JavaScript with the var, let, and const variables.
• And these variable declarations would be hoisted, but behave differently.

• Hoisting “var” variables

console.log(name)
var name = "Dillion“

• Here, we declare a variable called name with a string value of "Dillion".


But, we try to access the variable before the line it was declared. But we
don't get any errors. Hoisting happened.
• The name declaration is hoisted to the top, so the interpreter "knows"
that there is a variable called name. If the interpreter did not know, you
would get name is not defined.
• With variables declared var, the variable declaration is hoisted but with a
default value of undefined. The actual value is initialized when the
declaration line is executed.
70
Hoisting in JavaScript
 Variable Hoisting

• Hoisting “let” variables

• Although variables declared with let are also hoisted, they have a different
behavior.
console.log(name)
let name = "Dillion“
• Here, we get a reference error: Cannot access 'name' before initialization.
• Do you notice that the error does not say name is not defined? That's because the
interpreter is "aware" of a name variable because the variable is hoisted.
• "Cannot access 'name' before initialization" occurs because variables declared with
let do not have a default value when hoisted. As we saw in var, the variables have
a default value of undefined until the line where the declaration/initialization is
executed. But with let, the variables are uninitialized.
• The variables are hoisted to the top of the scope they are declared in (local, global,
or block), but are not accessible because they have not been initialized. This
concept is also referred to as the Temporal Dead Zone.
71
Hoisting in JavaScript
 Variable Hoisting

• Hoisting “const” variables

• just like let, variables declared with const are hoisted, but not accessible.
• The same concept of a temporal dead zone applies to const variables.
• Such variables are hoisted to the top of the scope they are defined in (local, global,
or block), but they remain inaccessible until the variables are initialized with a
value.

72
Hoisting in JavaScript
Temporal Dead Zone

• The temporal dead zone (TDZ) is a specific period in the execution of JavaScript code where
variables declared with let and const exist but cannot be accessed or assigned any value.
During this phase, accessing or using the variable will result in a ReferenceError.
• The TDZ ends and the variable becomes accessible after its declaration and initialization.
• The TDZ ensures that variables are accessed only after they have been properly declared and
initialized, promoting better coding practices and reducing the likelihood of accessing variables
in an undefined or uninitialized state.
• It’s worth noting that the TDZ does not apply to var variables. They are hoisted to the top of
their scope and can be accessed throughout the scope, even before their actual declaration.
• In summary, the TDZ is a period during which let and const variables exist but are not yet
accessible. It helps catch potential issues caused by accessing variables before their initialisation,
ensuring more reliable and predictable code.

73
Hoisting in JavaScript
 Class Hoisting

Classes in JavaScript are also hoisted.

const Dog = new Animal("Bingo")


class Animal {
constructor(name) {
this.name = name
}
}

• Here, we declare a class called Animal. We try to access this class (instantiate a Dog object) before it
was declared. We get a reference error: Cannot access 'Animal' before initialization.
• Just like let and const variables, classes are hoisted to the top of the scope they are defined in, but
inaccessible until they are initialized.
• We do not get "Animal is not defined", which shows that the interpreter "knows" that there is an
Animal class (due to hoisting). But we cannot access that class until the line of initialization is
executed.
74
Closure in JavaScript
 Functional programming

 Functional programming is all about functions

 In a language that supports functional programming, functions are generally


first-class objects. That means they can be assigned to variables, stored in
data structures, passed into functions and returned from functions.

 In JavaScript, it’s important to distinguish between referencing a function


and calling a function. To reference a function, just use the function name.
To call a function, append parentheses (with optional arguments).
function f() {
alert('f called!');
}
f(); // calls f
var x = f; // f is a reference to the function, and now x is too
x(); // calls f (or x - they're the same thing) 75
Closure in JavaScript
 Functional programming

 It’s also possible to create anonymous functions in JavaScript


function () {
alert('I have no name');
}

 Another name for an anonymous function is a function literal. If you imagine


it like a string literal you’ll see it’s an expression just like any other literal, and
so it can be assigned to a variable
var f = function () {
alert("I've been assigned to f");
}; //function literal

76
Closure in JavaScript
 Functional programming

 Another capability of functional languages is the ability to nest functions. It’s


perfectly valid in JavaScript to define one function within another.
function outer() {
function inner() {
alert('Inner function');
}
inner(); // we can call inner here as it is defined in outer's scope
}
inner(); // Error - but not here - inner is not defined in this scope

 It’s this ability, coupled with the first-class nature of functions, that
enables closures.

77
Closure in JavaScript
 What is a Scope Chain?

 A scope chain refers to the unique spaces that exist from the scope where a
variable got called to the global scope.

// Define a variable in the global scope:


const fullName = "Oluwatobi Sofela";

// Define nested functions:


function profile() {
function sayName() {
function writeName() {
return fullName;
}
return writeName();
}
return sayName();
} 78
Closure in JavaScript
 What is a Scope Chain?

 In the snippet above, observe that the fullName variable got called from the
writeName() function's scope.

 Therefore, the scope chain that exists from the variable’s call to the global
scope is:

writeName() scope ---> sayName() scope ---> profile() scope ---> global scope

 In other words, there are four (4) spaces from fullName’s invocation scope to
its lexical scope (the global scope in this instance).

79
Closure in JavaScript
 How Does the Scope Chain Work?
 JavaScript's scope chain determines the hierarchy of places the computer must go through
— one after the other — to find the lexical scope (origin) of the specific variable that got
called.
 since the code in writeName() instructs the computer to call and return the fullName
variable's content, the computer will call fullName. But it will not go directly to the global
scope to call fullName.
1. Firstly, the computer will check if fullName got defined locally within the
writeName() function. But it will find no fullName definition there, so it moves up
to the next scope to continue its quest.
2. Secondly, the computer will search for fullName's definition in sayName() (the
next space in the scope chain). Still, it doesn't find it there, so it climbs up the
ladder to the next scope.
3. Thirdly, the computer will search for fullName's definition in the profile() function.
Yet still, fullName is not found there. So the computer goes forward to seek
fullName's lexical scope in the next region of the scope chain.
4. Fourthly, the computer goes to the global scope (the following scope after
profile()). Fortunately, it finds fullName's definition there! Therefore, it gets its
content ("Oluwatobi Sofela") and returns it. 80
Closure in JavaScript

 Some things to keep in mind

 Suppose the computer did not find fullName's definition in any of the
scopes. In such a case, the computer will return Uncaught ReferenceError:
fullName is not defined.

 The global scope is always the last scope of any JavaScript scope chain. In
other words, the global scope is where all searches will end.

 An inner (child) scope has access to its parent (outer) scope, but an outer
scope does not have access to its child scope.

81
Closure in JavaScript
 What Does Lexical Mean?
 Lexical refers to the “definition of things”.
 Anything related to creation of words, expressions, or variables is
termed lexical.

 What is Lexical Scope in JavaScript?


 Lexical scope is the definition area of an expression.
 In other words, an item's lexical scope is the place in which the item
got created.
 A JavaScript expression’s definition environment determines the code
permitted to access it.
 In other words, only code within an item's lexical scope can access it.

82
Closure in JavaScript
 What are closures?

Closures are functions that have access to the variables that are present in
their scope chain even if the outer function ceases to exist.

Even if the outer function ceases to exist,


it still has access to its parent variables.

 Closures do not store static values.


 Instead, they store references to the variables present inside the scope
chain.
 In this way, even if the outer function dies, the inner function, that is a
closure, still has access to its parent variables.

83
Closure in JavaScript
 What are closures?

const add = (function () {


let counter = 0;
return function () {
counter += 1;
return counter
}
})();

add();
add();
add();

// the counter is now 3


84
Closure in JavaScript

 Advantages of closures

1. They allow you to attach variables to an execution context.


2. Variables in closures can help you maintain a state that you can use later.
3. They provide data encapsulation.
4. They help remove redundant code.
5. They help maintain modular code.

 Disadvantages of closures

1. The variables declared inside a closure are not garbage collected.


2. Too many closures can slow down your application. This is actually caused
by duplication of code in the memory.

85
Interview Questions…
1. What is the difference between parameters and arguments?
2. What are default parameters in JavaScript functions?
3. What is the rest parameter in JavaScript function?
4. What does return keyword do in JavaScript function?
5. What are arrow functions in JavaScript?
6. What are the callback functions in JavaScript?
7. What is default parameter in function? What is the use of it?
8. What is rest parameter? What is the use of it?
9. What is hoisting in JavaScript? Explain variable hoisting. Explain Function
hoisting.
10. What is scope chain? How does it work?
11. What is lexical scope in JavaScript?
86
12. What are closures in JavaScript functions? Explain with example and uses.
JavaScript Arrays
 An array is a special variable, which can hold more than one value:
 An array can hold many values under a single name, and you can access the
values by referring to an index number.

 Syntax
const array_name = [item1, item2, ...];
 It is a common practice to declare arrays with the const keyword.

 Spaces and line breaks are not important. A declaration can span multiple lines

 You can also create an array, and then provide the elements
Example : const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";
87
JavaScript Arrays
 Using the JavaScript Keyword new
 const cars = new Array("Saab", "Volvo", "BMW");

 Accessing Array Elements


 You access an array element by referring to the index number.
 Example const cars = ["Saab", "Volvo", "BMW"];
let car = cars[0];
 Array indexes start with 0.

 Arrays are Objects But, JavaScript arrays are best described as arrays.

 Array Elements Can Be Objects

88
JavaScript Arrays
 Array Properties and Methods
 The real strength of JavaScript arrays are the built-in array properties
and methods.

 The length Property


const fruits = ["Banana", "Orange", "Apple", "Mango"];
let length = fruits.length;

 Accessing the First Array Element


let fruit = fruits[0];

 Accessing the Last Array Element


let fruit = fruits[fruits.length - 1];

89
JavaScript Arrays
 The Difference Between Arrays and Objects
 In JavaScript, arrays use numbered indexes.
 In JavaScript, objects use named indexes.

 When to Use Arrays. When to use Objects.


 You should use objects when you want the element names to be strings
(text).
 You should use arrays when you want the element names to
be numbers.

90
JavaScript Array Methods

 toString()
 It converts an array to a string of (comma separated) array values.
fruits.toString();

 pop()
 It method removes the last element from an array
let fruit = fruits.pop();

 push()
 This method adds a new element to an array (at the end)
fruits.push("Kiwi");

91
JavaScript Array Methods
 shift()
 This method removes the first array element and "shifts" all other
elements to a lower index.
 Shifting is equivalent to popping, but working on the first element
instead of the last.
fruits.shift();
 unshift()
 This method adds a new element to an array (at the beginning), and
"unshifts" older elements
fruits.unshift("Lemon");
 delete()
 Array elements can be deleted using the JavaScript operator delete
 Using delete leaves undefined holes in the array.
 Use pop() or shift() instead.
delete fruits[0];
92
JavaScript Array Methods
 from()
 The Array.from() method returns an Array object from any object with a
length property or any iterable object.

 Syntax
Array.from(object, mapFunction, thisValue);
object: This parameter holds that object that will convert into
an array
mapFunction: This parameter is optional and used to call on
each item of the array.

 Example
Create an Array from a String:
Array.from("ABCDEFG") // Returns [A,B,C,D,E,F,G]
Array.from([1, 2, 3], (x) => x + x)
93
JavaScript Array Methods
 splice()
 This method can be used to add new items to an array
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
• The first parameter (2) defines the position where new elements should
be added (spliced in)
• The second parameter (0) defines how many elements should be removed
• The rest of the parameters ("Lemon" , "Kiwi") define the new elements to
be added

 With clever parameter setting, you can use splice() to remove elements
without leaving "holes" in the array
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0, 1);
• The first parameter (0) defines the position where new elements should
be added (spliced in).
• The second parameter (1) defines how many elements should be removed. 94
JavaScript Array Methods
 slice()
 This method slices out a piece of an array into a new array.

const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];


const citrus = fruits.slice(1);

 Slice method creates a new array.


 This method does not remove any elements from the source array

 It can take two arguments like slice(1,3)


 The method then selects elements from the start argument, and up to
(but not including) the end argument.

 If the end argument is omitted, this method slices out the rest of the
array.
95
JavaScript Array Methods
 concat()
 It does not change the existing arrays. It always returns a new array.
 This method creates a new array by merging (concatenating) existing arrays
const myGirls = ["Cecilie", "Lone"];
const myBoys = ["Emil", "Tobias", "Linus"];
const myChildren = myGirls.concat(myBoys);

 It can take any number of array arguments


const arr1 = ["Cecilie", "Lone"];
const arr2 = ["Emil", "Tobias", "Linus"];
const arr3 = ["Robin", "Morgan"];
const myChildren = arr1.concat(arr2, arr3);

 It can also take strings as arguments


const arr1 = ["Emil", "Tobias", "Linus"];
const myChildren = arr1.concat("Peter"); 96
JavaScript Sorting Arrays
 Sort()
 Alphabetically sort
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();

 Numeric Sort
 By default, the sort() function sorts values as strings.
 This works well for strings ("Apple" comes before "Banana").
 However, if numbers are sorted as strings, "25" is bigger than "100",
because "2" is bigger than "1".
 Because of this, the sort() method will produce incorrect result when
sorting numbers.
 You can fix this by providing a compare function
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});
97
JavaScript Sorting Arrays
 Find the Highest (or Lowest) Array Value
 However, after you have sorted an array, you can use the index to
obtain the highest and lowest values.

 Using Math.max() on an Array


 You can use this method to find the highest number in an array
function myArrayMax(arr) {
return Math.max.apply(null, arr);
}

 Using Math.min() on an Array


 You can use this method to find the lowest number in an array
function myArrayMin(arr) {
return Math.min.apply(null, arr);
}
98
JavaScript Sorting Arrays

 Sorting Object Arrays


 Even if objects have properties of different data types, the sort() method can
be used to sort the array.
 The solution is to write a compare function to compare the property values.

const cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}
];

cars.sort(function(a, b){return a.year - b.year});

99
JavaScript Sorting Arrays

 Comparing string properties is a little more complex

cars.sort(function(a, b){
let x = a.toLowerCase();
let y = b.toLowerCase();
if (x < y) {return -1;}
if (x > y) {return 1;}
return 0;
});

-1 means the first goes before the second, 1 means it goes after,
and 0 means they're equivalent.

100
JavaScript Sorting Arrays
 Reverse()
 This method reverses the elements in an array.
 You can use it to sort an array in descending order
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
fruits.reverse();
 filter()
 This method creates a new array with array elements that pass a test
const numbers = [45, 4, 9, 16, 25];
const over18 = numbers.filter(myFunction);

function myFunction(value, index) {


return value > 18;
}
In the example above, the callback function does not use the index and
array parameters, so they can be omitted 101
JavaScript Sorting Arrays

 reduce()
 This method runs a function on each array element to produce (reduce it to)
a single value. It works from left-to-right in the array.
 It does not reduce the original array.
const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduce(myFunction);

function myFunction(total, value, index, array) {


return total + value;
}

 reduceRight()
 Same as reduce(). It works from right-to-lft in the array.
 Same Example
102
JavaScript Sorting Arrays
 every()
 This method checks if all array values pass a test.
const numbers = [45, 4, 9, 16, 25];
let allOver18 = numbers.every(myFunction);

function myFunction(value, index, array) {


return value > 18; // true or false
}
 some()
 This method checks if some array values pass a test.
const numbers = [45, 4, 9, 16, 25];
let someOver18 = numbers.some(myFunction);

function myFunction(value, index, array) {


return value > 18;
} 103
JavaScript Sorting Arrays
 indexOf()
 This method searches an array for an element value and returns its position.
 returns -1 if the item is not found.
 Syntax
array.indexOf(item, start)
item is required
start is optional
Example
const fruits = ["Apple", "Orange", "Apple", "Mango"];
let position = fruits.indexOf("Apple") + 1;

 lastIndexOf()
 Same as of indexOf() but returns the position of the last occurrence of the
specified element. Looks for from right to left.
const fruits = ["Apple", "Orange", "Apple", "Mango"];
let position = fruits.lastIndexOf("Apple") + 1; 104
JavaScript Sorting Arrays
 find()
 Find() method returns the value of the first array element that passes a test
function.
const numbers = [4, 9, 16, 25, 29];
let first = numbers.find(myFunction);
function myFunction(value, index, array) {
return value > 18;
}
 findIndex()
 This method returns the index of the first array element that passes a test
function.
const numbers = [4, 9, 16, 25, 29];
let first = numbers.findIndex(myFunction);
function myFunction(value, index, array) {
return value > 18;
} 105
JavaScript Sorting Arrays
 includes()
 This allows us to check if an element is present in an array (including NaN,
unlike indexOf).
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.includes("Mango"); // is true

 Spread Operator (...)


 The spread operator (...) expands an iterable (like an array) into more
elements.
 Add the values of an array to the new one.
const q1 = ["Jan", "Feb", "Mar"];
const q2 = ["Apr", "May", "Jun"];
const q3 = ["Jul", "Aug", "Sep"];
const q4 = ["Oct", "Nov", "May"];
const year = [...q1, ...q2, ...q3, ...q4];
106
JavaScript Array Const
 In 2015, JavaScript introduced an important new keyword const.
 An array declared with const can not be reassigned.

 Arrays are Not Constants


 The keyword const is little misleading.
 It does NOT define a constant array. It defines a constant reference to an
array.
 Because of this, we can still change the elements of a constant array.

 Elements Can be Reassigned


 You can change the elements of a constant array
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Toyota"; //change “Toyota” to index 0.
cars.push("Audi");

107
JavaScript Array Const
 Assigned when Declared
 Const variables must be assigned a value when they are declared
 An array declared with const must be initialized when it is declared.
 Using const without initializing the array is a syntax error
This will not work:
const cars;
cars = ["Saab", "Volvo", "BMW"];

 Const Block Scope


 An array declared with const has a block scope.
 An array declared with var does not have a block scope.
 An array declared in a block is not the same as an array declared outside the
block

108
JavaScript Array Const
 Redeclaring Arrays

 Redeclaring an array declared with var is allowed anywhere in a program


var cars = ["Volvo", "BMW"]; // Allowed
var cars = ["Toyota", "BMW"]; // Allowed
cars = ["Volvo", "Saab"]; // Allowed

 Redeclaring or reassigning an array to const in the same scope, or in the


same block, is not allowed
var cars = ["Volvo", "BMW"]; // Allowed
const cars = ["Volvo", "BMW"]; // Not allowed
{
var cars = ["Volvo", "BMW"]; // Allowed
const cars = ["Volvo", "BMW"]; // Not allowed
}
109
JavaScript Array Const
 Redeclaring Arrays

 Redeclaring or reassigning an existing const array, in the same scope, or in


the same block, is not allowed
const cars = ["Volvo", "BMW"]; // Allowed
const cars = ["Volvo", "BMW"]; // Not allowed
var cars = ["Volvo", "BMW"]; // Not allowed
cars = ["Volvo", "BMW"]; // Not allowed

{
const cars = ["Volvo", "BMW"]; // Allowed
const cars = ["Volvo", "BMW"]; // Not allowed
var cars = ["Volvo", "BMW"]; // Not allowed
cars = ["Volvo", "BMW"]; // Not allowed
}
110
JavaScript Array Const
 Redeclaring Arrays

 Redeclaring an array with const in another scope, or in another block, is


allowed
const cars = ["Volvo", "BMW"]; // Allowed
{
const cars = ["Volvo", "BMW"]; // Allowed
}
{
const cars = ["Volvo", "BMW"]; // Allowed
}

111
Interview Questions…
1. What are arrays in JavaScript? How to create an array?
2. What is the difference between arrays and objects?
3. How to access elements inside the arrays in JavaScript?
4. How to find the length of an array?
5. How to access the first element in an array?
6. How to access last element inside an array?
7. What does array.pop() method do? OR How to remove last element from
an array in JavaScript?
8. What does array.push() method do? OR How to add element to last
position in an array in JavaScript?
9. What does array.shift() method do? OT How to remove first element of an
array in JavaScript??
112
Interview Questions…
1. What does array.unshift() method do? OR How to add an element in the
first position inside an array in JavaScript?
2. What does array.toString() method do?
3. What does array.splice() method do?
4. How to merge two different arrays? OR What does array.concat() method
do and how to use it?
5. What does array.filter() method do?
6. What does array.reduce() method do?
7. What does array.indexOf() method do?
8. What is spread operator? What does it do?

113
JavaScript Strings
 JavaScript strings are for storing and manipulating text.
 A JavaScript string is zero or more characters written inside quotes.

 Because strings must be written within quotes, JavaScript will misunderstand this
string

let text = "We are the so-called "Vikings" from the north.";

 The solution to avoid this problem, is to use the backslash escape character.

let text = "We are the so-called \"Vikings\" from the north.";

let text= 'It\'s alright.';

114
JavaScript Strings Methods
 All string methods return a new string. They don't modify the original string.
 Strings are immutable: Strings cannot be changed, only replaced.

 length
 This property returns the length of a string.
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = text.length;

 slice()
 It extracts a part of a string and returns the extracted part in a new string.
 The method takes 2 parameters: start position, and end position (end not
included).
let text = "Apple, Banana, Kiwi";
let part = text.slice(7, 13);
 If a parameter is negative, the position is counted from the end of the string.
let part = text.slice(-12); 115
JavaScript Strings Methods

 substring()
 It is similar to slice().
 The difference is that start and end values less than 0 are treated as 0 in
substring()
let str = "Apple, Banana, Kiwi";
let part = str.substring(7, 13);

 substr()
 It is similar to slice().
 The difference is that the second parameter specifies the length of the
extracted part.
let str = "Apple, Banana, Kiwi";
let part = str.substr(7, 6);

116
JavaScript Strings Methods
 replace()
 This method replaces a specified value with another value in a string.
let text = "Please visit Microsoft!";
let newText = text.replace("Microsoft", “Apple");
 It does not change the string it is called on.
 It method returns a new string.
 It replaces only the first match.
 It is case sensitive.
 ReplaceAll()
 In 2021, JavaScript introduced the string method replaceAll().
 This method allows you to specify a regular expression instead of a string to
be replaced.
let text = "I love cats. Cats are very easy to love. Cats are very
popular.“
text1 = text.replaceAll("Cats","Dogs");
text2 = text.replaceAll("cats","dogs"); 117
JavaScript Strings Methods
 toUpperCase()
 A string is converted to upper case
let text1 = "Hello World!";
let text2 = text1.toUpperCase();

 toLowerCase()
 A string is converted to lower case
let text1 = "Hello World!";
let text2 = text1.toLowerCase();

 concat()
 It can be used instead of the plus operator.
 It joins two or more strings
text = "Hello" + " " + "World!";
text = "Hello".concat(" ", "World!");
118
JavaScript Strings Methods
 trim()
 It removes whitespace from both sides of a string
let text1 = " Hello World! ";
let text2 = text1.trim();

 trimStart()
 Works like trim(), but removes whitespace only from the start of a string
let text1 = " Hello World! ";
let text2 = text1.trimStart();

 trimEnd()
 Works like trim(), but removes whitespace only from the end of a string.
let text1 = " Hello World! ";
let text2 = text1.trimEnd();

119
JavaScript Strings Methods
 charAt()
 This method returns the character at a specified index (position) in a string.
let text = "HELLO WORLD";
let char = text.charAt(0);

 lastIndexOf()
 It returns the index of the last occurrence of a specified text in a string
let str = "Please locate where 'locate' occurs!";
str.lastIndexOf("locate");

 indexOf()
 It returns the index of (position of) the first occurrence of a string in a string
let str = "Please locate where 'locate' occurs!";
str.indexOf("locate");

120
JavaScript Strings Methods
 search()
 This method searches a string for a string (or a regular expression) and
returns the position of the match
let str = "Please locate where 'locate' occurs!";
str.search("locate");
 startsWith()
 This method returns true if a string begins with a specified value.
let text = "Hello world, welcome to the universe.";
text.startsWith("Hello");
text.startsWith("world", 5)

 endsWith()
 This method returns true if a string ends with a specified value.
let text = "John Doe";
text.endsWith("Doe");
121
JavaScript Strings Methods
 includes()
 It returns true if a string contains a specified value.
let text = "Hello world, welcome to the universe.";
text.includes("world");

text.includes("world", 12);

122
Interview Questions…
1. How to create string variables in JavaScript?
2. How to find out the length of the string in JavaScript?
3. What does text.slice() method do in JavaScript?
4. What is the difference between text.slice() and text.substr() methods in
JavaScript?
5. How to replace a text in a sentence using JavaScript?
6. What is the difference between text.replace() and text.replaceAll()
method in JavaScript?
7. How to convert upper case to lower case and vice-a-versa in JavaScript
strings?
8. How to merge two strings in JavaScript?
9. What does text.includes() method do in JavaScript?
123
JavaScript Numbers
 JavaScript has only one type of number. Numbers can be written with or without
decimals
 JavaScript Numbers are Always 64-bit Floating Point

 Integer Precision
 Integers (numbers without a period or exponent notation) are accurate up to
15 digits.
let x = 999999999999999; // x will be 999999999999999
let y = 9999999999999999; // y will be 10000000000000000
 The maximum number of decimals is 17.

 Floating Precision
 Floating point arithmetic is not always 100% accurate:
let x = 0.2 + 0.1;
let x = (0.2 * 10 + 0.1 * 10) / 10; // it helps
124
JavaScript Numbers
 Adding Numbers and Strings
 JavaScript uses the + operator for both addition and concatenation.
 Numbers are added. Strings are concatenated.

• If you add two numbers, the result will be a number.


• If you add two strings, the result will be a string concatenation.
• If you add a number and a string, the result will be a string concatenation.
• If you add a string and a number, the result will be a string concatenation

 Numeric Strings
 JavaScript will try to convert strings to numbers in all numeric operations
let x = "100";
let y = "10";
let a = x / y; // It will work
let b = x * y; // It will work
let c = x - y; // It will work 125
JavaScript Numbers
 NaN - Not a Number
 It is a JavaScript reserved word indicating that a number is not a legal
number.
 Trying to do arithmetic with a non-numeric string will result in NaN.
let x = 100 / "Apple";
 However, if the string contains a numeric value , the result will be a number.
let x = 100 / "10";

 isNaN()
 You can use the global JavaScript function isNaN() to find out if a value is a
not a number.
let x = 100 / "Apple";
isNaN(x);

126
JavaScript Numbers
 Infinity
 It is the value JavaScript will return if you calculate a number outside the
largest possible number.
let x = 2 / 0;

127
JavaScript Numbers
 JavaScript Numbers as Objects
 Normally JavaScript numbers are primitive values created from literals.
let x = 123;
 But numbers can also be defined as objects with the keyword
let y = new Number(123);

• Do not create Number objects.


• The new keyword complicates the code and slows down execution speed.
• Number Objects can produce unexpected results

 Imagine we need to write 1 billion. The obvious way is :


let billion = 1000000000;

 We also can use underscore ( _ ) as a separator.


let billion = 1_000_000_000;
128
JavaScript Numbers
 toString()
 This method returns a number as a string.
let x = 123;
x.toString();

 parseInt()
 returns an integer
parseInt('100px')

 parseFloat()
 return a floating-point number
parseFloat('12.5em')

129
Interview Questions…
1. What is integer precision in JavaScript numbers?
2. What is floating point precision in JavaScript numbers?
3. How to find if the values is numbers or not? OR What is isNaN() method
used for?
4. What is the use of underscore (_) in JavaScript?
5. What does number.toString() do in JavaScript?
6. What does number.parseInt() do in JavaScript? How to draw an integer
value from a string containing number and character?
7. What does number.parseFloat() do in JavaScript? How to draw a float
value from a string containing float number and character?

130
JavaScript Math Object
 The JavaScript Math object allows you to perform mathematical tasks on numbers.
• Unlike other objects, the Math object has no constructor.
• The Math object is static.
• All methods and properties can be used without creating a Math object first.

 Math Properties
 JavaScript provides 8 mathematical constants that can be accessed as Math
properties
Math.E // returns Euler's number
Math.PI // returns PI
Math.SQRT2 // returns the square root of 2
Math.SQRT1_2 // returns the square root of 1/2
Math.LN2 // returns the natural logarithm of 2
Math.LN10 // returns the natural logarithm of 10
Math.LOG2E // returns base 2 logarithm of E
Math.LOG10E // returns base 10 logarithm of E 131
JavaScript Math Object
Math Methods
 The syntax for Math any methods is Math.method(number)

 Number to Integer
There are few common methods to round a number to an integer

 Math.round()
 returns the nearest integer
Math.round(4.6);
 Math.ceil()
 returns the value of x rounded up to its nearest integer
Math.floor(4.2)
 Math.floor()
 returns the value of x rounded down to its nearest integer
Math.floor(4.9)
132
JavaScript Math Object
 Math.trunc()
 returns the integer part of x
Math.trunc(4.9);
 Math.sign()
 returns if x is negative (-1), null(0) or positive(1)
Math.sign(-4);
 Math.log10()
 returns the base-10 logarithm of a number.
Math.log10(2)
 Math.log2()
 method returns the base-2 logarithm of a number.
Math.log2(2.7183)
 Math.pow()
 returns the value of x to the power of y
Math.pow(8, 2);
133
JavaScript Math Object
 Math.sqrt()
 returns the square root of x
Math.sqrt(64);
 Math.cbrt()
 method returns the cubic root of a number.
Math.cbrt(125)
 Math.abs()
 returns the absolute (positive) value of x
Math.abs(-4.7);
 Math.sin()
 returns the sine (a value between -1 and 1) of the angle x (given in
radians).
 If you want to use degrees instead of radians, you have to convert
degrees to radians
 Angle in radians = Angle in degrees x PI / 180.
Math.sin(90 * Math.PI / 180); // returns 1 (the sine of 90 degrees)134
JavaScript Math Object
 Math.cos()
 returns the cosine (a value between -1 and 1) of the angle x (given in
radians).
 If you want to use degrees instead of radians, you have to convert
degrees to radians
 Angle in radians = Angle in degrees x PI / 180.
Math.cos(0 * Math.PI / 180); // returns 1 (the cos of 0 degrees)

 Math.min() and Math.max()


 can be used to find the lowest or highest value in a list of arguments
Math.min(0, 150, 30, 20, -8, -200);
Math.max(0, 150, 30, 20, -8, -200);

135
JavaScript Math Object
 Math.random()

 returns a random number between 0 (inclusive), and 1 (exclusive)


 always returns a number lower than 1.

Math.random(); // Returns a random number:

 JavaScript Random Integers

 Math.random() is used with math.floor() can be used to return


random integers.

 There is no such thing as JavaScript integers.

136
JavaScript Math Object

 Returns a random integer from 0 to 9:


Math.floor(Math.random() * 10);
 Returns a random integer from 0 to 10:
Math.floor(Math.random() * 11);
 Returns a random integer from 0 to 99:
Math.floor(Math.random() * 100);
 Returns a random integer from 0 to 100:
Math.floor(Math.random() * 101);
 Returns a random integer from 1 to 10:
Math.floor(Math.random() * 10) + 1;
 Returns a random integer from 1 to 100:
Math.floor(Math.random() * 100) + 1;

137
JavaScript Math Object

 Returns a random alphanumeric key of 20 digits :


var a = Array.from(
Array(20),
() => Math.floor(Math.random() * 36).toString(36)
).join('');

 Array(20) => Array of 20 indexes with empty element values


 toString(2/8/16/32)
 The Array.from() static method creates a new, shallow-copied Array
instance from an iterable or array-like object.
 Syntax
 Array.from(arrayLike, mapFn)

138
Interview Questions…
1. What does Math.round() do?
2. What does Math.ceil() do?
3. What does Math.floor() do?
4. What does Math.pow() do?
5. What does Math.sqrt() do? OR How to calculate the square root of a
number using math object in JavaScript?
6. What does Math.cbrt() do? OR How to calculate the cube root of a
number using math object in JavaScript?
7. What does Math.random() do? How to generate a random number using
math object in JavaScript?
8. How to generate the random 4/5/6 digit number using math object in
JavaScript?
139
JavaScript Set Object
 A set is a collection of items that are unique i.e. no element can be repeated.
 Set in ES6 are ordered: elements of the set can be iterated in the insertion order.
 The set can store any type of value whether primitive or objects.
 Set objects are collections of values. A value in the set may only occur once

 How to Create a Set ?


const letters = new Set(); // creates an empty set
let set3 = new Set([10, 20, 30, 30, 40, 40]); // it contains [10, 20, 30, 40]
let set2 = new Set("fooooooood"); // it contains 'f', 'o', 'd'

 Points to remember
1. A set object uses the concept of keys internally.
2. A set object cannot contain the duplicate values.
3. A set object iterates its elements in insertion order.

140
JavaScript Set Object
 Set Methods

 add()
Adds a new element to the Set
letters.add("a");
set1.add(10);
set1.add(30).add(40).add(50);

 delete()
It deletes an element with the specified value from the Set object.
set1.delete('e')

 clear()
It removes all the element from the set.
set1.clear();
141
JavaScript Set Object
 Set Methods

 has()
It returns true if the specified value is present in the Set object.
set1.has(50)

 forEach()
It executes the given function once for every element in the Set, in the
insertion order.
// Create a Set
const letters = new Set(["a","b","c"]);

// List all entries


let text = "";
letters.forEach (function(value) {
text += value;
}) 142
JavaScript Set Object
 Set Methods
 values()
It returns all the values from the Set in the same insertion order.
This method does not take any parameter
set1.values();
 entries()
It returns an iterator object which contains an array having the entries
of the set, in the insertion order.
This method does not take any parameter
set1.entries();
 keys()
It also returns all the values from the Set in the insertion order.
It is similar to the values() in the case of Sets
This method does not take any parameter
set1.keys();
143
JavaScript Set Object
 Set Operations

No pre-defined set operations in JavaScript.

 Union
const unionSet = new Set([...setA, ...setB]);

 Intersection
const intersectionSet = new Set([...setA].filter(x => setB.has(x)));

 Difference
const differenceSet = new Set([...setA].filter(x => !setB.has(x)));

144
JavaScript Map Object
 JavaScript map is a collection of elements where each element is stored as a Key,
value pair.
 Map objects can hold both objects and primitive values as either key or value.
 When we iterate over the map object returns the key, and value pair in the same
order as inserted.
 A key in the Map may only occur once; it is unique in the Map's collection.

 Objects vs. Maps


 Object is similar to Map—both let you set keys to values, retrieve those values, delete keys,
and detect whether something is stored at a key. For this reason (and because there were
no built-in alternatives), Object has been used as Map historically.
 A Map is an iterable, so it can be directly iterated. Object does not implement an iteration
protocol, and so objects are not directly iterable using the JavaScript for...of statement (by
default).
 A Map's keys can be any value (including functions, objects, or any primitive). The keys of an
Object must be either a String or a Symbol.
145
JavaScript Map Object
 How to Create a Map
You can create a Map by passing an Array to the new Map() constructor

const fruits = new Map(); // create empty map


const fruits = new Map([ // create map with multiple elements
["apples", 500],
["bananas", 300],
["oranges", 200]
]);

 Map methods
 set()
stores the value by the key.
const fruits = new Map();
fruits.set("apples", 500);
fruits.set("bananas", 300);
146
JavaScript Map Object
 Map methods
 get()
returns the value by the key, undefined if key doesn’t exist in map.
fruits.get("apples"); // Returns 500

 clear()
Removes all the elements from a Map
fruits.clear();

 delete()
Removes a Map element specified by a key
fruits.delete("apples");

 has()
Returns true if a key exists in a Map
fruits.has("apples"); 147
JavaScript Map Object
 Map methods

 forEach()
Invokes a callback for each key/value pair in a Map
myMap.forEach((value, key) => {
console.log(`${key} = ${value}`);
});

 entries()
Returns an iterator object with the [key, value] pairs in a Map. it’s used
by default in for..of.
for (const x of fruits.entries()) {
console.log(x[0]);
}

148
JavaScript Map Object
 Map methods

 keys()
Returns an iterator object with the keys in a Map
for (const x of fruits.keys()) {
console.log(x);
}

 values()
Returns an iterator object of the values in a Map
for (const x of fruits.values()) {
console.log(x);
}

149
150
Interview Questions…
1. What is set object in JavaScript?
2. Explain set object methods with its use.
add(), delete(), clear(), has(), forEach(), values(), entries(), keys().
3. What is map object in Javscript?
4. Explain map object methods with its use.
get(), delete(), clear(), has(), forEach(), values(), entries(), keys().
5. what is the difference between set object and map object in Javscript?

151
JavaScript Object
 You have already learned that JavaScript variables are containers for data values.
 Objects are variables too. But objects can contain many values.
 Example
const car = {
type:"Fiat",
model:"500",
color:"white“
};
 The values are written as name : value pairs (name and value separated by a colon).
 It is a common practice to declare objects with the const keyword.
 Spaces and line breaks are not important. An object definition can span multiple
lines.

152
JavaScript Object
 Do Not Declare Strings, Numbers, and Booleans as Objects!

x = new String(); // Declares x as a String object


y = new Number(); // Declares y as a Number object
z = new Boolean(); // Declares z as a Boolean object

They complicate your code and slow down execution speed.

 Accessing Object Properties


 objectName.propertyName
 objectName["propertyName"]

153
JavaScript Object Methods & this keyword
 Method examples
let user = {
name: "John",
age: 30
};
user.sayHi = function() {
alert("Hello!");
};
user.sayHi(); // Hello!

• Here we’ve just used a Function Expression to create a function and assign it
to the property user.sayHi of the object.
• Then we can call it as user.sayHi(); The user can now speak!
• A function that is a property of an object is called its method.
• So, here we’ve got a method sayHi of the object user.
154
JavaScript Object Methods & this keyword
 “This” Keyword
 “this” holds value of an object that is executing the current function.
 It’s common that an object method needs to access the information stored
in the object to do its job.
 The value of this is the object “before dot”, the one used to call the method.
let user = {
name: "John",
age: 30,
sayHi() {
// "this" is the "current object"
alert(this.name);
}
};
user.sayHi(); // John
 Technically, it’s also possible to access the object without this, by referencing
it via the outer variable 155
JavaScript Object Methods & this keyword
 “This” Keyword
 …But such code is unreliable. If we decide to copy user to another variable,
e.g. admin = user and overwrite user with something else, then it will access
the wrong object.
let user = {
name: "John",
age: 30,
sayHi() {
alert( user.name ); // leads to an error
}
};
let admin = user;
user = null; // overwrite to make things obvious
admin.sayHi(); // TypeError: Cannot read property 'name' of null
• If we used this.name instead of user.name inside the alert then the code
would work. 156
JavaScript Object Methods & this keyword
 “this” is not bound

 In JavaScript, keyword this behaves unlike most other programming


languages. It can be used in any function, even if it’s not a method of an
object.

function sayHi() {
alert( this.name );
}
There’s no syntax error in the above code.

157
JavaScript Object Methods & this keyword

 For instance, here the same function is assigned to two different objects and
has different “this” in the calls.
let user = { name: "John" };
let admin = { name: "Admin" };
function sayHi() {
alert( this.name );
}
// use the same function in two objects
user.f = sayHi;
admin.f = sayHi;
// these calls have different this
// "this" inside the function is the object "before the dot"
user.f(); // John (this == user)
admin.f(); // Admin (this == admin)
158
JavaScript Object Methods & this keyword
 The consequences of unbound this

 If you come from another programming language, then you are probably used
to the idea of a "bound this”, where methods defined in an object always have
this referencing that object.
 In JavaScript this is “free”, its value is evaluated at call-time and does not
depend on where the method was declared, but rather on what object is
“before the dot”.
 The concept of run-time evaluated this has both pluses and minuses. On the
one hand, a function can be reused for different objects. On the other hand, the
greater flexibility creates more possibilities for mistakes.
 Here our position is not to judge whether this language design decision is good
or bad. We’ll understand how to work with it, how to get benefits and avoid
problems.

159
JavaScript Object Methods & this keyword
 Arrow functions have no “this”

 Arrow functions are special: they don’t have their “own” this. If we reference
this from such a function, it’s taken from the outer “normal” function.

 That’s a special feature of arrow functions, it’s useful when we actually do not
want to have a separate this but rather to take it from the outer context.

160
JavaScript Date Objects

 JavaScript Date Objects let us work with dates:


Thu Mar 09 2023 07:01:05 GMT+0530 (India Standard Time)

 Creation
 To create a new Date object, call new Date()
 There are 9 ways to create a new date object

• new Date()
 creates a date object with the current date and time
const d = new Date();

161
JavaScript Date Objects
• new Date(date string)
 creates a date object from a date string
const d = new Date("2022-03-25");

Date Formats
ISO Date : "2015-03-25" (The International Standard)
Short Date : "03/25/2015“
Long Date : "Mar 25 2015" or "25 Mar 2015“

• new Date( year, month)

 creates a date object with a specified date and time


 7 numbers specify year, month, day, hour, minute, second, and
millisecond (in that order)
const d = new Date(2018, 11, 24, 10, 33, 30, 0);
162
JavaScript Date Objects
• new Date( year, month) continued..

Note :
• JavaScript counts months from 0 to 11
• Specifying a month higher than 11, will not result in an error but
add the overflow to the next year
• Specifying a day higher than max, will not result in an error but add
the overflow to the next month.
• 6 numbers specify year, month, day, hour, minute, second
• 5 numbers specify year, month, day, hour, and minute
• 4 numbers specify year, month, day, and hour
• 3 numbers specify year, month, and day
• 2 numbers specify year and month
• You cannot omit month. If you supply only one parameter it will be
treated as milliseconds
163
JavaScript Date Objects
• new Date( year, month) continued…

Previous Century
• One and two digit years will be interpreted as 19xx

const d = new Date(99, 11, 24);


const d = new Date(9, 11, 24);

JavaScript Stores Dates as Milliseconds


One day (24 hours) is 86 400 000 milliseconds

164
JavaScript Date Objects
• new Date(milliseconds)
creates a new date object as milliseconds plus zero time

01 January 1970 plus 100 000 000 000 milliseconds is


const d = new Date(100000000000);

January 01 1970 minus 100 000 000 000 milliseconds is


const d = new Date(-100000000000);

January 01 1970 plus 24 hours is


const d = new Date(86400000);
const d = new Date(24 * 60 * 60 * 1000);

165
JavaScript Get Date Methods
Notes :
• The get methods above return Local time
• The get methods return information from existing date objects.
• In a date object, the time is static. The "clock" is not "running".
• The time in a date object is NOT the same as current time.

• getFullYear()
method returns the year of a date as a four digit number
const d = new Date();
d.getFullYear();

Notes :
• Old JavaScript code might use the non-standard method getYear().
• getYear() is supposed to return a 2-digit year.
• getYear() is deprecated. Do not use it!
166
JavaScript Get Date Methods
• getMonth()
method returns the month of a date as a number (0-11).
d.getMonth();

You can use an array of names to return the month as a name


Const months = [“January”, “February”, “March”, “April”, “May”,
“June”, “July”, “August”, “September”, “October”, “November”,
“December”]
const d = new Date("2021-03-25");
let month = months[d.getMonth()];

• getDate()
method returns the day of a date as a number (1-31)
d.getDate();
167
JavaScript Get Date Methods
• getDay()
method returns the weekday of a date as a number (0-6)
d.getDay();

You can use an array of names, and getDay() to return weekday as a


name
Const months = [“Sunday”, “Monday”, “Tuesday”, “Wednesday”,
“Thursday”, “Friday”, “Saturday”]
const d = new Date("2021-03-25");
let day = days[d.getDay()];

Notes :
• In JavaScript, the first day of the week (day 0) is Sunday.
• Some countries in the world consider the first day of the week
to be Monday.
168
JavaScript Get Date Methods
• getHours()
method returns the hours of a date as a number (0-23)
d.getHours();

• getMinutes()
method returns the minutes of a date as a number (0-59)
d.getMinutes();

• getSeconds()
method returns the seconds of a date as a number (0-59)
d.getSeconds();

• getMilliseconds()
method returns the milliseconds of a date as a number (0-999)
d.getMilliseconds();
169
JavaScript Get Date Methods

• getTime()
It returns the number of milliseconds since January 1, 1970
d.getTime()

• The Date.now() Method


It is a static method of the Date object.
returns the number of milliseconds since January 1, 1970.
let ms = Date.now();

170
JavaScript Get Date Methods
UTC Date Get Methods

 UTC methods use UTC time (Coordinated Universal Time).


 UTC time is the same as GMT (Greenwich Mean Time).
 The difference between Local time and UTC time can be up to 24
hours.

• getUTCDate()
• getUTCFullYear()
• getUTCMonth()
• getUTCDay()
• getUTCHours()
• getUTCMinutes()
• getUTCSeconds()
• getUTCMilliseconds()
171
JavaScript Set Date Methods
 Set Date methods let you set date values (years, months, days, hours, minutes,
seconds, milliseconds) for a Date Object.
 Set Date methods are used for setting a part of a date

• setFullYear()
method sets the year of a date object. In this example to 2020
const d = new Date();
d.setFullYear(2020);

method can optionally set month and day


d.setFullYear(2020, 11, 3);

• setMonth()
method sets the month of a date object (0-11)
d.setMonth(11);
172
JavaScript Set Date Methods
• setDate()
method sets the day of a date object (1-31)
d.setDate(15);

method can also be used to add days to a date


d.setDate(d.getDate() + 50);

• setHours()
method sets the hours of a date object (0-23)
d.setHours(22);

• setMinutes()
method sets the minutes of a date object (0-59)
d.setMinutes(30);

173
JavaScript Set Date Methods

• setSeconds()
method sets the seconds of a date object (0-59)
d.setSeconds(30);

174
Interview Questions…
1. What is Date object? What does it do?
2. How to create a new Date object?
3. Explain all the get methods of date object.
4. Explain all the set methods of data object.

175
The modern mode, "use strict"

 It defines that JavaScript code should be executed in "strict mode".


 The purpose of “user strict” is to indicate that the code should be executed in
"strict mode".
 With strict mode, you can not, for example, use undeclared variables.

 Declaring Strict Mode


 Strict mode is declared by adding “use strict” to the beginning of a script
or a function.
 Declared at the beginning of a script, it has global scope (all code in the
script will execute in strict mode):
 Declared inside a function, it has local scope (only the code inside the
function is in strict mode):

176
The modern mode, "use strict"
 Why Strict Mode?

 Strict mode makes it easier to write "secure" JavaScript.


 Strict mode changes previously accepted "bad syntax" into real errors.
 As an example, in normal JavaScript, mistyping a variable name creates a
new global variable. In strict mode, this will throw an error, making it
impossible to accidentally create a global variable.
 In normal JavaScript, a developer will not receive any error feedback
assigning values to non-writable properties.
 In strict mode, any assignment to a non-writable property, a getter-only
property, a non-existing property, a non-existing variable, or a non-
existing object, will throw an error.

177
JavaScript Modules
 JavaScript modules allow you to break up your code into separate files.
 A module is just a file. One script is one module. As simple as that.
 A module is a function or group of similar functions. They are grouped together
within a file and contain the code to execute a specific task when called into a
larger application.
 You create modules to better organize and structure your codebase.
 You can use them to break down large programs into smaller, more manageable,
and more independent chunks of code which carry out a single or a couple of
related tasks.
 Modules should be:
• Independent/Self-contained: A module has to be as detached from other
dependencies as possible.
• Specific: A module needs to be able to perform a single or a related group of tasks. The
core essence of creating them in the first place is to create separate functionalities. One
module, one (kind of) task.
• Reusable: A module has to be easy to integrate into various kinds of programs to
perform its task. 178
JavaScript Modules

 Exports

1. Named Exports
You can create named exports two ways. In-line individually, or all at
once at the bottom.
// one export in a line
export const name = "Jesse";
export const age = 40;

const name = “Jesse”;


const age = 40;
// multiple exports in one line
export { name, age }

179
JavaScript Modules

2. Default Exports

You can only have one default export in a file.


const message = () => {
const name = "Jesse";
const age = 40;
return name + ' is ' + age + 'years old.';
};

export default message;

180
JavaScript Modules
 Imports
• Modules are imported from external files with the import statement.
• Modules also rely on attribute type="module" in the <script> tag.
<script type="module" src="main.js"></script>
• You can import modules into a file in two ways, based on if they are
named exports or default exports.
• Named exports are constructed using curly braces. Default exports are
not.

Import from named exports


import { name, age } from "./person.js";

Import from default exports


import message from "./message.js";

181
Interview Questions…
1. What is the use of "use strict" in JavaScript? OR what is strict mode in
JavaScript?
2. What are JavaScript modules? What are they used for?
3. Name the types of JavaScript modules?
4. What is the difference between named exports and default exports?
5. How to import default exports in JavaScript files?
6. How to import named exports in JavaScript files?

182
JavaScript JSON
 JSON is a popular data exchange format that represents data as key-value pairs.
 JSON is a format for storing and transporting data.
 JSON is often used when data is sent from a server to a web page.

 What is JSON?
• JSON stands for JavaScript Object Notation
• JSON is a lightweight data interchange format
• JSON is language independent
• JSON is "self-describing" and easy to understand

 The JSON syntax is derived from JavaScript object notation syntax, but the JSON
format is text only. Code for reading and generating JSON data can be written in
any programming language.

183
JavaScript JSON
 JSON Syntax Rules
• Data is in name/value pairs
• Data is separated by commas
• Curly braces hold objects
• Square brackets hold arrays

 Example
{
Name : ”your name”,
Id : 1234,
obj : {
title : ”Something”,
},
languages : [“html”, “css”, “js”]
}
184
JavaScript JSON Methods
 JSON.stringify()

 It’s easy to use JSON for data exchange when the client uses JavaScript
and the server is written on Ruby/PHP/Java/Whatever.

let student = {
stringValue: 'John',
numValue: 30,
boolValue: false,
arrValue: ['html', 'css', 'js'],
nullValue: null
};
let json = JSON.stringify(student);

185
JavaScript JSON Methods
 JSON.parse()

 Use the JavaScript built-in function json.parse() to convert the string into a
JavaScript object

let text = '{


"employees" : [
' + ' { "firstName":"John" , "lastName":"Doe" },
' + '{ "firstName":"Anna" , "lastName":"Smith" },
' + '{ "firstName":"Peter" , "lastName":"Jones" }
]
}';

const obj = JSON.parse(text);

186
JavaScript Events
 HTML events are "things" that happen to HTML elements.
 When JavaScript is used in HTML pages, JavaScript can "react" on these events.

 HTML Events
 An HTML event can be something the browser does, or something a user
does.
 Here are some examples of HTML events:
• An HTML web page has finished loading
• An HTML input field was changed
• An HTML button was clicked
 JavaScript lets you execute code when events are detected.

 Syntax
<element onclick=“handleClickEvent()”>

187
JavaScript Events

 Common HTML Events

• Onchange() - An HTML element has been changed

• Onclick() - The user clicks an HTML element

• Onmouseover() - The user moves the mouse over an HTML element

• Onmouseout() - The user moves the mouse away from an HTML element

• Onkeydown() - The user pushes a keyboard key

• Onload() - The browser has finished loading the page

188
JavaScript Events
 Examples
<input value="Click me" onclick="alert('Click!')" type="button">

 addEventListener
 Syntax
element.addEventListener(event, handler, [options]);
event : Event name, e.g. onclick (required)
handler : The handler function. (required)
[options] : An additional optional object with properties (optional)
 Example
const btn = document.getElementById("myBtn");
btn.addEventListener("click", myFunction);
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
189
JavaScript Events
 btn.addEventListener("click", myFunction);

 Instead of ”click” you can use following events as well.


 change
 dblclick
 focus
 keyup
 keypressed
 load
 mouseover
 mouseout
 scroll
 submit
…..
 & Others
190
Interview Questions…
1. What is JSON? Explain.
2. What does JSON.stringify() do?
3. What does JSON.parse() do?
4. What are HTML events? What are common html events?
5. Explain addEventListner() function in JavaScript?

191
Browser Environment, Specifications
 DOM (Document Object Model)

 The Document Object Model, or


DOM for short, represents all page
content as objects that can be
modified.
 DOM is not only for browsers

 BOM (Browser Object Model)

 The Browser Object Model (BOM)


represents additional objects
provided by the browser (host
environment) for working with
everything except the document.
 For Example window, screen,
location, history, navigation etc.
192
JavaScript - HTML DOM
 What is the DOM?
 The DOM is a W3C (World Wide Web Consortium) standard. The DOM defines a
standard for accessing documents
 Document Object Model (DOM) is a platform and language-neutral interface that allows
programs and scripts to dynamically access and update the content, structure, and style
of a document."

 What is the HTML DOM?


The HTML DOM is a standard object model and programming interface for HTML. It
defines
• The HTML elements as objects
• The properties of all HTML elements
• The methods to access all HTML elements
• The events for all HTML elements

 When a web page is loaded, the browser creates a Document Object Model of the page.
 The HTML DOM model is constructed as a tree of Objects
193
JavaScript - HTML DOM Tree

194
JavaScript - HTML DOM Methods & Properties
 HTML DOM methods are actions you can perform (on HTML Elements).
 HTML DOM properties are values (of HTML Elements) that you can set or
change.

 The getElementById Method


 The most common way to access an HTML element is to use the id of an
element.
 The innerHTML Property
 The easiest way to get the content of an element is by using the
innerHTML property.

 Example
document.getElementById("demo").innerHTML = "Hello World!";

195
JavaScript - HTML DOM Methods & Properties
 Finding HTML Elements

 document.getElementById(id)
Find an element by element id
const element = document.getElementById("intro");

 document.getElementsByTagName(name)
Find elements by tag name
const element = document.getElementsByTagName("p");

 document.getElementsByClassName(name)
Find elements by class name
const x = document.getElementsByClassName("intro");

196
JavaScript - HTML DOM Methods & Properties
 Changing HTML Elements
 element.innerHTML = new html content
Change the inner HTML of an element
document.getElementById("p1").innerHTML = "New text!";

 element.attribute = new value


Change the attribute value of an HTML element
document.getElementById(id).attribute = new value

 element.style.property = new style


Change the style of an HTML element
document.getElementById("p2").style.color = "blue";

 element.setAttribute(attribute, value)
Change the attribute value of an HTML element
document.getElementById("myH1").setAttribute("class", "democlass");
197
JavaScript - HTML DOM Methods & Properties
 Adding and Deleting Elements

Considering the below example for createElement(), appendChild() &


removeChild() methods.

<div id="headingDiv">
<h1 id="h1Tag">This is an h1 Tag</h1>
<h2 class="h2Tag">This is an h2 Tag</h2>
</div>

let divElement = document.getElementById("headingDiv");


let h1Element = document.getElementById("h1Tag");
let h2Element = document.getElementById("h2Tag");

198
JavaScript - HTML DOM Methods & Properties
 Adding and Deleting Elements
 document.createElement(element)
- Create an HTML element
Let h3Element = document.createElement("h3");
Let h3ElementContent = document.createTextNode("This is h3 Tag");
h3Element.appendChild(h3ElementContent);
document.body.appendChild(h3Element);

 document.removeChild(element)
- Remove an HTML element
divElement.removeChild(h1Element);

 document.appendChild(element)
- Add an HTML element
h3Element.appendChild(h3ElementContent);
199
JavaScript - HTML DOM Methods & Properties
 Adding and Deleting Elements
 document.replaceChild(new, old)
- Replace an HTML element
<ul id="myList">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>

<script>
function myFunction() {
// Select first child element:
const element = document.getElementById("myList").children[0];
// Create a new text node:
const newNode = document.createTextNode("Water");
// Replace the text node:
element.replaceChild(newNode, element.childNodes[0]);
}
</script> 200
JavaScript - HTML DOM Methods & Properties
 Adding and Deleting Elements

 document.write(text)
Write into the HTML output stream
• It writes directly to an open (HTML) document stream.
• deletes all existing HTML when used on a loaded document.

document.write("<h2>Hello World!</h2><p>Have a nice day!</p>");

201
JavaScript - HTML DOM Methods & Properties
 Target particular element inside a particular <div> element.
const x = document.getElementById("main");
const y = x.getElementsByTagName("p");

 querySelectorAll()
It can access the html elements using the class, id, attribute, attribute value or
tag name. It works just like CSS selectors.
const x = document.querySelectorAll(“.intro");
This example returns a list of all elements with class=“intro”

const x = document.querySelectorAll(“#intro");
This example returns a list of all elements with id=“intro”

const x = document.querySelectorAll("p.intro");
This example returns a list of all <p> elements with class=“intro”
202
JavaScript - HTML DOM Methods & Properties
 DOM Nodes
 According to the W3C HTML DOM standard, everything in an HTML
document is a node
• The entire document is a document node
• Every HTML element is an element node
• The text inside HTML elements are text nodes
• Every HTML attribute is an attribute node (deprecated)
• All comments are comment nodes

 Node Relationships
• In a node tree, the top node is called the root (or root node)
• Every node has exactly one parent, except the root (which has no parent)
• A node can have a number of children
• Siblings (brothers or sisters) are nodes with the same parent

203
JavaScript - HTML DOM Node Tree

204
JavaScript Forms

 JavaScript Email Validation

if (/\S+@\S+\.\S+/.test(inpEmail)){
Console.log(“email id is properly formatted”)
}
else{
console.log(“email id is not properly formatted”)
}

205
JavaScript Browser Object Model (BOM)
 The Browser Object Model (BOM) allows JavaScript to "talk to" the browser.

 The Window Object


 It represents the browser's window.
 All global JavaScript objects, functions, and variables automatically
become members of the window object.
 Global variables are properties of the window object.
 Global functions are methods of the window object.

 Window Size
 Two properties can be used to determine the size of the browser
window.

let w = window.innerWidth;
let h = window.innerHeight;
206
JavaScript Browser Object Model (BOM)
 Window Screen
screen.width
screen.height
screen.availWidth
screen.availHeight

 Window History (contains the browsers history.)

 History Back
This is the same as clicking the Back button in the browser.
window.history.back()

 History Forward
This is the same as clicking the Forward button in the browser.
window.history.forward()
207
JavaScript Browser Object Model (BOM)
 Window Navigator

 Browser Version
returns version information about the browser
navigator.appVersion;
 Browser Agent
returns the user-agent header sent by the browser to the
server
navigator.userAgent
 Browser Platform
returns the browser platform (operating system)
navigator.platform
 Browser Language
property returns the browser's language
navigator.language
208
JavaScript Browser Object Model (BOM)
 Window Navigator

 Is Java Enabled?
returns true if Java is enabled
navigator.javaEnabled()

 Is The Browser Online?


returns true if the browser is online
navigator.onLine

209
Accessing current location of a user
<body>
<h2>JavaScript Geolocation</h2>
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script>
const myElement = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); }
else { myElement.innerHTML = "Geolocation is not supported by this browser.";}
}

function showPosition(position) {
myElement.innerHTML =
"Latitude: " +
position.coords.latitude +
"<br>Longitude: " +
position.coords.longitude;
}
</script>
</body> 210
Interview Questions…
1. What is HTML DOM? What is HTML DOM tree?
2. What is BOM?
3. What is the difference between DOM and BOM?
4. What are the different ways to access the HTML elements inside the html DOM?
5. How to set the new attribute of any html element?
6. How to change the attribute value of any html element?
7. How to change the css property of any html element?
8. How to add another html element inside html DOM?
9. What is querySelector() method? what is it used for?
10. What is querySelectorAll() method? what is it used for?
11. What is the difference between window.innerwidth and screen.width?
12. How to fetch the information about the user's system using window navigator
211
object?
Storing Data in JavaScript
Cookies

 Cookies let you store user information in web pages.

 Cookies are data, stored in small text files, on your computer.

 When a web server has sent a web page to a browser, the connection is shut
down, and the server forgets everything about the user. Cookies were
invented to solve the problem "how to remember information about the
user“.

 JavaScript can create, read, and delete cookies with the document.cookie
property.

212
Storing Data in JavaScript

 Create a Cookie

 With JavaScript, a cookie can be created like


document.cookie = "username=John Doe";

 You can also add an expiry date (in UTC time).


document.cookie = "username=John Doe; expires=Thu, 18 Dec 2023 12:00:00 UTC";
Note : By default, the cookie is deleted when the browser is closed
(400 DAYS Max.)

 With a path parameter, you can tell the browser what path the cookie
belongs to. By default, the cookie belongs to the current page.
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2023 12:00:00 UTC;
path=/";
Note : Usually, we should set path to the root path=/ to make the
213
cookie accessible from all website pages.
Storing Data in JavaScript

 Read a Cookie

let x = document.cookie;
document.cookie will return all cookies in one string much like:
cookie1=value; cookie2=value; cookie3=value;

 Change a Cookie

you can change a cookie the same way as you create it

document.cookie = "username=John Smith; expires=Thu, 18 Dec 2013


12:00:00 UTC; path=/";

Note : Old cookie is overwritten


214
Storing Data in JavaScript

 Delete a Cookie

 Deleting a cookie is very simple.


 You don't have to specify a cookie value when you delete a cookie.
 Just set the expires parameter to a past date:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC;


path=/";

Note :
• You should define the cookie path to ensure that you delete the
right cookie.
• Some browsers will not let you delete a cookie if you don't
specify the path.
215
Storing Data in JavaScript

 Cookie String
 Document.cookie property looks like a normal text string. But it is not.
 Even if you write a whole cookie string to document.cookie, when you
read it out again, you can only see the name-value pair of it.
 If you set a new cookie, older cookies are not overwritten. The new
cookie is added to document.cookie, so if you read document.cookie
again you will get something like : cookie1 = value; cookie2 = value;
 If you want to find the value of one specified cookie, you must write a
JavaScript function that searches for the cookie value in the cookie
string.

Note : There’s no way to let a cookie be accessible from another 2nd-


level domain, so other.com will never receive a cookie set at site.com

216
Storing Data in JavaScript

Notes :

• There’s no way to let a cookie be accessible from another 2nd-level


domain, so other.com will never receive a cookie set at site.com

• By default, if we set a cookie at http://site.com then it also appears


at https://site.com and vice versa.
document.cookie = "user=John; secure";

217
Web Storage API in JavaScript
Local Storage
 The localStorage object provides access to a local storage for a particular Web
Site. It allows you to store, read, add, modify, and delete data items for that
domain.
 The data does not expire. It remains after the browser restart and even OS
reboot.
 Shared between all tabs and windows from the same origin.
 Please note that both key and value must be strings.
setItem()
localStorage.setItem("name", "John Doe");
It takes key and value as parameters
getItem()
localStorage.getItem("name");
It takes only key as a parameter
removeItem()
localStorage.removeItem("name"); 218
Web Storage API in JavaScript
Session Storage
 sessionStorage object is used much less often than localStorage Object.
 The sessionStorage object is identical to the localStorage object.
 The difference is that the sessionStorage object stores data for one session.
 The data survives page refresh, but not closing/opening the tab.
 Another tab with the same page will have a different storage.
 But it is shared between iframes in the same tab (assuming they come from
the same origin).
setItem()
sessionStorage.setItem("name", "John Doe");
It takes key and value as parameters
getItem()
sessionStorage.getItem("name");
It takes only key as a parameter
removeItem()
sessionStorage.removeItem("name"); 219
Cookie, Local Storage & Session Storage

Notes :

• Unlike cookies, web storage objects are not sent to server with each
request. Because of that, we can store much more. Most modern browsers
allow at least 5 megabytes of data (or more) and have settings to configure
that.
• Also unlike cookies, the server can’t manipulate storage objects via HTTP
headers. Everything’s done in JavaScript.
• The storage is bound to the origin (domain/protocol/port triplet). That is,
different protocols or subdomains infer different storage objects, they
can’t access data from each other.

220
Interview Questions…
1. What is the difference between web storage API's and cookies?
2. What is the difference between local storage and session storage?
3. How to add data, read data and delete data from session storage and local
storage?
4. What are cookies and how to create them?
5. How to read, update and delete cookies?
6. What is the use of "path" attribute in the cookie?
7. What is the use of "secure" attribute in the cookie?

221
JavaScript Fetch API
 API stands for Application Programming Interface.
 In the context of APIs, the word Application refers to any software with a
distinct function.
 Interface can be thought of as a contract of service between two applications.
 This contract defines how the two communicate with each other using
requests and responses.

222
JavaScript Fetch API

 The Fetch API interface allows web browser to make HTTP requests to web
servers.

 JavaScript can send network requests to the server and load new information
whenever it’s needed.

 For example, we can use a network request to


• Submit an order,
• Load user information,
• Receive latest updates from the server,
• …etc.

 …And all of that without reloading the page!

223
JavaScript Fetch API
 Example
fetch("http://jsonplaceholder.typicode.com/posts")
.then((response) => response.json())
.then((data) => console.log(data))
.catch(error=>console.log(error))
 Example Explained
 You are calling the Fetch API and passing in the URL to the JSONPlaceholder API.
 Then a response is received. However, the response you get is not JSON, but an
object with a series of methods that can be used depending on what you want to
do with the information. To convert the object returned into JSON, use the json()
method
 Add the then() method which will contain a function with a parameter called
response
 The JSON data still needs to be processed. Add another then() statement with a
function that has an argument called data
 With both then() functions completed, you can now add the catch() function. This
function will log the potential error to the console: 224
JavaScript Fetch Post-API
 Example
let data = {
title: "foo",
body: "bar",
userId: 1,
};

fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
body: JSON.stringify(data),
headers: { "Content-type": "application/json; charset=UTF-8" },
})
.then((response) => response.json())
.then((json) => console.log(json))
.catch((err) => console.log(err));

225
JavaScript Async/Await
 Async functions
 It can be placed before a function, like this:
async function f() {
return 1;
}
 The word “async” before a function means one simple thing: a function
always returns a promise. Other values are wrapped in a resolved promise
automatically.
 Await
let value = await promise;
 The keyword await makes JavaScript wait until that promise settles and
returns its result.
 The function execution “pauses” and resumes when the promise settles.
 Cant use await in a regular function.
 Error handling
 Use catch block to handle the errors 226
JavaScript Promises
 The Promise object represents the eventual completion (or failure) of an
asynchronous operation and its resulting value.
 A Promise contains both the producing code and calls to the consuming code

 A Promise is in one of these states:


• pending: initial state, neither fulfilled nor rejected.
• fulfilled: meaning that the operation was completed successfully.
• rejected: meaning that the operation failed.

 Syntax
let promise = new Promise(function(resolve, reject) {
// executor (the producing code, "singer")
});
• The function passed to new Promise is called the executor.
• Its arguments resolve and reject are callbacks provided by JavaScript itself. Our code is
only inside the executor.
227
JavaScript Promises
 Example
let promise = new Promise(function (resolve, reject) {
const x = “nikhil";
const y = “nikhil"
if (x === y) { resolve(); }
else { reject(); }
});

promise
.then(function () {
console.log('Success, You are a GEEK');
})
.catch(function () {
console.log('Some error has occurred');
});

228
JavaScript Promises
1. Promise then() Method

It is invoked when a promise is either resolved or rejected. It may also be


defined as a carrier that takes data from promise and further executes it
successfully.

- It takes two functions as parameters.


1. The first function is executed if the promise is resolved and a result is received.
2. The second function is executed if the promise is rejected and an error is received.
(It is optional and there is a better way to handle error which is using .catch()
method

.then(function(result){
//handle success
}, function(error){
//handle error
})
229
JavaScript Promises
2. Promise catch() Method

It is invoked when a promise is either rejected or some error has occurred in


execution. It is used as an Error Handler whenever at any step there is a
chance of getting an error.

- It takes one function as a parameter.


1. Function to handle errors or promise rejections.(.catch() method internally calls
.then(null, errorHandler), i.e. .catch() is just a shorthand for .then(null, errorHandler)
)

.catch(function(error){
//handle error
})

230
JavaScript Promises
You cannot access the Promise properties state and result.
You must use a Promise method to handle promises.

2. Promise catch() Method

It is invoked when a promise is either rejected or some error has occurred in


execution. It is used as an Error Handler whenever at any step there is a
chance of getting an error.

- It takes one function as a parameter.


1. Function to handle errors or promise rejections.(.catch() method internally calls
.then(null, errorHandler), i.e. .catch() is just a shorthand for .then(null, errorHandler)
)

.catch(function(error){
//handle error
}) 231
JavaScript Try..Catch..finally
 No matter how great we are at programming, sometimes our scripts have errors.
They may occur because of our mistakes, an unexpected user input, an erroneous
server response, and for a thousand other reasons.
 Usually, a script “dies” (immediately stops) in case of an error, printing it to
console.
 But there’s a syntax construct try...catch that allows us to “catch” errors so the
script can, instead of dying, do something more reasonable.
try {
tryCode - Code block to run
}
catch(err) {
catchCode - Code block to handle errors
}
finally {
finallyCode - Code block to be executed regardless of the try result
}
• A try statement lets you test a block of code for errors.
• A catch statement lets you handle that error. 232
• The finally statement defines a code block to run regardless of the result.
JavaScript Try..Catch..finally
 tryCode
Required.
Code block to be tested while executing.

 err
A local reference to the error object.
err.name (Error, syntaxError, and so on)
err.message( actual error message)

 catchCode
Optional.
Code block to execute if an error occurs.

 FinallyCode
Optional.
Code block to execute regardless of the try result 233
JavaScript Try..Catch..finally
 The “throw” Statement

• The throw statement allows you to create a custom error.


• Technically you can throw an exception (throw an error).
• The exception can be a JavaScript String, a Number, a Boolean or an
Object:

throw "Too big"; // throw a text


throw 500; // throw a number

234
JavaScript Try..Catch..finally
In JavaScript, a try...catch block is used to handle exceptions (errors) that occur during the execution
of code. Here's when and why you should use it:

 Error Handling: Whenever there's a possibility of an error occurring in your code, you should use a
try...catch block to gracefully handle those errors. Errors can occur due to various reasons such as
invalid input, network issues, or unexpected conditions.
 Preventing Program Crashes: Without error handling, if an error occurs during the execution of
your code, it might cause the program to crash. By using try...catch, you can catch these errors and
prevent the entire program from crashing. Instead, you can handle the error appropriately and
continue execution or provide useful feedback to the user.
 Asynchronous Code: When dealing with asynchronous operations like fetching data from a server
or reading files, errors might occur during these operations. Using try...catch helps in handling
errors that occur within asynchronous functions.
 Debugging: try...catch blocks can also be useful during development for debugging purposes. You
can catch errors, log them, and examine the stack trace to understand what went wrong.

235
Interview Questions…
1. What is fetch API? What is it used for?
2. What is an API? How does an API works?
3. Explain fetch API with syntax?
4. What is the use of async/await? what does it do? and where can we use it?
5. What are promises in JavaScript?
6. How to create a new promise? Explain .then() and .catch() blocks.
7. Explain try/catch block? What does it do?
8. What does throw statement so inside the try/catch block?

236
JavaScript Classes

 A JavaScript class is not an object.

 It is a template for JavaScript objects.

 In JavaScript, a class is a kind of function.

 In object-oriented programming, a class is an extensible program-code-template


for creating objects, providing initial values for state (member variables) and
implementations of behavior (member functions or methods).

237
JavaScript Classes

 Syntax
class ClassName {
constructor() { ... }
}

 Example
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}

238
JavaScript Classes
 The Constructor Method
• It has to have the exact name "constructor"
• It is executed automatically when a new object is created
• It is used to initialize object properties
 If you do not define a constructor method, JavaScript will add an empty
constructor method.

 Class Methods
 Class methods are created with the same syntax as object methods.
 Syntax
class ClassName {
constructor() { ... }
method_1() { ... }
method_2() { ... }
method_3() { ... }
} 239
JavaScript Classes
 Create a Class method named "age", that returns the Car age:
<p id="demo"></p>
<script>
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
age() {
const date = new Date();
return date.getFullYear() - this.year;
}
}
const myCar = new Car("Ford", 2014);
document.getElementById("demo").innerHTML = "My car is " + myCar.age() + " years old.;
</script>

240
JavaScript Classes
 Class Inheritance
 To create a class inheritance, use the extend keyword
 A class created with a class inheritance inherits all the methods from another class
 The super keyword is used to call the constructor of its parent class to access the
parent's properties and methods.
class Car {
constructor(brand) {
this.carname = brand;
}
present() { return 'I have a ' + this.carname; }
}
class Model extends Car {
constructor(brand, mod) {
super(brand);
this.model = mod;
}
show() { return this.present() + ', it is a ' + this.model; }
}
let myCar = new Model("Ford", "Mustang");
document.getElementById("demo").innerHTML = myCar.show(); 241
JavaScript Classes
 Inheritance is useful for code reusability: reuse properties and methods
of an existing class when you create a new class.
 Static Methods
 Static class methods are defined on the class itself.
 You cannot call a static method on an object, only on an object class.
class Car {
constructor(name) {
this.name = name;
}
static hello() {
return "Hello!!";
}
}
const myCar = new Car("Ford");

// You can call 'hello()' on the Car Class:


document.getElementById("demo").innerHTML = Car.hello();
// But NOT on a Car Object:
// document.getElementById("demo").innerHTML = myCar.hello();
242
// this will raise an error.
JavaScript Classes
 If you want to use the myCar object inside the static method, you can
send it as a parameter:

class Car {
constructor(name) {
this.name = name;
}
static hello(x) {
return "Hello " + x.name;
}
}
const myCar = new Car("Ford");
document.getElementById("demo").innerHTML = Car.hello(myCar);

243
JavaScript Popup Boxes
 Alert
 method displays an alert box with a message and an OK button.
 method is used when you want information to come through to the user.
 The alert box takes the focus away from the current window, and forces the user to
read the message.
alert('alert opened')

 Prompt
 method displays a dialog box that prompts the user for input.
 method returns the input value if the user clicks "OK", otherwise it returns null
 A prompt box is used if you want the user to input a value.
prompt('prompt opened')

 Confirm
 method displays a dialog box with a message, an OK button, and a Cancel button
 method returns true if the user clicked "OK", otherwise false.
 A confirm box is often used if you want the user to verify or accept something.
244
confirm('confirm opened')
JavaScript Insert Icons
 FontAwesome

 Insert the following code inside your html <head> tag

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/f


ont-awesome/4.7.0/css/font-awesome.min.css">

Note : You will have to generate your own <script> src link to
access the icons.

 Use the icons like below


<i class="fa-solid fa-folder"></i>
<i style="font-size: 10px" class="fa-solid fa-bars"></i>

245
JavaScript Scheduling: setTimeout and setInterval
 We may decide to execute a function not right now, but at a certain time later.
That’s called “scheduling a call”.

 setTimeout()
 This method calls a function after a number of milliseconds.
 executed only once.
setTimeout(function, milliseconds, param1, param2, ...)

function sayHi() { alert('Hello'); }


setTimeout(sayHi, 1000);

 Function or a string of code to execute. Usually, that’s a function. For


historical reasons, a string of code can be passed, but that’s not
recommended.
 The delay before run, in milliseconds (1000 ms = 1 second), by
default 0. 246
JavaScript Scheduling: setTimeout and setInterval
 setInterval()
 This method calls a function at specified intervals (in milliseconds).
 All arguments have the same meaning. But unlike setTime it runs the
function not only once, but regularly after the given interval of time.
 To clear an interval, use the id returned from setInterval()
 Then you can to stop the execution by calling clearInterval()
const timerId = setInterval(() => {
console.log("code to be executed repeatedly on specific intervals");
}, 1000);

setTimeout(() => {
clearInterval(timerId);
console.log("msg to display that code execution has been stopped");
}, 10000);

 The above example will show the message every 1 seconds. After 10
seconds, the output is stopped
247
Interview Questions…
1. What is the difference between alert(), prompt() and confirm()?
2. What is the difference between setTimeout() and setInterval()?
3. how to stop setInterval()?

248
JavaScript Best Practices
 Avoid Global Variables

 Always Declare Local Variables

 Declarations on Top

 Initialize Variables
Avoid undefined values

 Declare Objects with const


Declaring objects with const will prevent any accidental change of type

 Declare Arrays with const


Declaring arrays with const will prevent any accidential change of type

 Don't Use new Object() 249


JavaScript Best Practices
 Beware of Automatic Type Conversions
• JavaScript is loosely typed.
• A variable can contain all data types.
• A variable can change its data type
• Beware that numbers can accidentally be converted to strings or NaN
• When doing mathematical operations, JavaScript can convert numbers to strings
• Subtracting a string from a string, does not generate an error but returns NaN

 Use === Comparison


• == comparison operator always converts (to matching types) before comparison.
• === operator forces comparison of values and type:

 End Your Switches with Defaults


• Even if you think there is no need for it

 Avoid Number, String, and Boolean as Objects


• Always treat numbers, strings, or booleans as primitive values. Not as objects.
• Declaring these types as objects, slows down execution speed, and produces nasty side 250
effects
JavaScript Common Mistakes
 Accidentally Using the Assignment Operator
• JavaScript programs may generate unexpected results if a programmer accidentally uses
an assignment operator (=) instead of a comparison operator (==)

 Expecting Loose Comparison

 Confusing Addition & Concatenation


• Addition is about adding numbers.
• Concatenation is about adding strings.

 Misunderstanding Floats
• All numbers in JavaScript are stored as 64-bits Floating point numbers (Floats).

 Breaking a JavaScript String


• JavaScript will allow you to break a statement into two lines
• But, breaking a statement in the middle of a string will not work:
251
JavaScript Common Mistakes
 Misplacing Semicolon

 Breaking a Return Statement


• Never break a return statement.

 Accessing Arrays with Named Indexes


• Many programming languages support arrays with named indexes.
• Arrays with named indexes are called associative arrays (or hashes).
• JavaScript does not support arrays with named indexes.
• In JavaScript, arrays use numbered indexes.
• In JavaScript, objects use named indexes.

 Ending Definitions with a Comma

 Undefined is Not Null

252
JavaScript Performance
 How to speed up your JavaScript code.

 Reduce Activity in Loops


• Statements or assignments that can be placed outside the loop will make the
loop run faster.
• The bad code accesses the length property of an array each time the loop is
iterated.
• The better code accesses the length property outside the loop and makes the
loop run faster.

 Reduce DOM Access


• Accessing the HTML DOM is very slow, compared to other JavaScript
statements.
• If you expect to access a DOM element several times, access it once, and use it
as a local variable

 Avoid Unnecessary Variables


253
JavaScript Performance
 Reduce DOM Size
• Keep the number of elements in the HTML DOM small.
• This will always improve page loading, and speed up rendering (page display), especially
on smaller devices.
• Every attempt to search the DOM (like getElementsByTagName) will benefit from a
smaller DOM.

 Delay JavaScript Loading


 Putting your scripts at the bottom of the page body lets the browser load the
page first.
 While a script is downloading, the browser will not start any other downloads.
In addition all parsing and rendering activity might be blocked.
 If possible, you can add your script to the page by code, after the page has
loaded
<script>
window.onload = function() {
const element = document.createElement("script");
element.src = "myScript.js";
document.body.appendChild(element);
254
}; </script>
JavaScript vs JQuery

 JQuery was created in 2006 by John Resig. It was designed to handle Browser
Incompatibilities and to simplify HTML DOM Manipulation, Event Handling,
Animations, and Ajax.

 jQuery is a small and lightweight JavaScript library.


 jQuery means "write less do more".
 jQuery simplifies AJAX call and DOM manipulation.

 For more than 10 years, jQuery has been the most popular JavaScript library in
the world.

 However, after JavaScript Version 5 (2009), most of the jQuery utilities can be
solved with a few lines of standard JavaScript:

255
JavaScript vs JQuery
 What You Should Already Know
• HTML
• CSS
• JavaScript

 Adding jQuery to Your Web Pages


 Downloading jQuery
• Download the jQuery library from jQuery.com
• The jQuery library is a single JavaScript file, and you reference it
with the HTML <script> tag (notice that the <script> tag should be
inside the <head> section
<head>
<script src="jquery-3.6.3.min.js"></script>
</head>

256
JavaScript vs JQuery
 Adding jQuery to Your Web Pages
 jQuery CDN
• If you don't want to download and host jQuery yourself, you can
include it from a CDN (Content Delivery Network).
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery
/3.6.3/jquery.min.js"></script>
</head>

 jQuery Syntax
 Basic syntax is: $(selector).action()
• A $ sign to define/access jQuery
• A (selector) to "query (or find)" HTML elements
• A jQuery action() to be performed on the element(s)

257
JavaScript vs JQuery
 Finding HTML Element by Id
JS --> myElement = document.getElementById("id01");
Jquery --> myElement = $("#id01");

 Finding HTML Elements by Tag Name


JS --> myElements = document.getElementsByTagName("p");
Jquery --> myElements = $("p");

 Finding HTML Elements by Class Name


JS --> myElements = document.getElementsByClassName("intro");
Jquery --> myElements = $(".intro");

 Finding HTML Elements by CSS Selectors


JS --> myElements = document.querySelectorAll("p.intro");
Jquery --> myElements = $("p.intro");
258
JavaScript Ajax
$.ajax({
url: 'https://dummyjson.com/products',
type: 'get',
dataType: 'json',
success: function (response) {
console.log("something");
},
error: function (error) {
console.log(error)
},
always: function () {

}
})

259
Coding Challenges and Exercises
1. https://www.jschallenger.com/
2. https://clean-code.io/
3. https://codeguppy.com/blog/javascript-coding-challenges-for-beginners/index.html
4. https://github.com/rradfar/javascript-coding-challenges
5. https://www.keka.com/javascript-coding-interview-questions-and-answers
6. https://www.fullstack.cafe/blog/javascript-code-interview-questions
7. https://www.educative.io/
8. https://www.thatjsdude.com/interview/js1.html
9. https://www.thatjsdude.com/interview/js2.html
10. https://github.com/jwill9999/JavaScript-Array-Interview-Practice
11. https://medium.com/@sagormahtab/10-javascript-coding-challenges-that-you-might-
face-in-interview-b3e2f029a076
12. https://codeinterview.io/blog/javascript-coding-interview-questions/
13. https://www.freecodecamp.org/news/javascript-projects-for-beginners/
14. https://github.com/sadanandpai/javascript-code-challenges
15. https://javascript.plainenglish.io/50-questions-to-master-the-javascript-coding-
interview-639d2ac12630

260

You might also like