JS
JS
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.
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.
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>
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>
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);
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);
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
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;
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
27
JavaScript Operators
Assignment 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
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
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
Example
using if Else statement
let a;
if (age > 18) { a = true; }
else { a = false; }
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.
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
}
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
}
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.
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
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:
1. Write comments
2. Split functions into smaller functions
3. Using Promises
4. Using Async/await
64
JavaScript Callbacks/ Callback Functions
Sequence Control
• 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;
}
myCalculator(5, 5, myDisplayer);
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.
console.log(name)
var name = "Dillion“
• 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
• 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
• 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
76
Closure in JavaScript
Functional programming
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.
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
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.
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.
83
Closure in JavaScript
What are closures?
add();
add();
add();
Advantages of closures
Disadvantages of closures
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");
Arrays are Objects But, JavaScript arrays are best described as arrays.
88
JavaScript Arrays
Array Properties and Methods
The real strength of JavaScript arrays are the built-in array properties
and methods.
89
JavaScript Arrays
The Difference Between Arrays and Objects
In JavaScript, arrays use numbered indexes.
In JavaScript, objects use named indexes.
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.
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);
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.
const cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}
];
99
JavaScript Sorting Arrays
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);
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);
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);
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
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"];
108
JavaScript Array Const
Redeclaring Arrays
{
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
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.";
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.
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);
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)
135
JavaScript Math Object
Math.random()
136
JavaScript Math Object
137
JavaScript Math Object
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
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"]);
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.
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!
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
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
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“
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
164
JavaScript Date Objects
• new Date(milliseconds)
creates a new date object as milliseconds plus zero time
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();
• 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();
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()
170
JavaScript Get Date Methods
UTC Date Get Methods
• 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);
• 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);
• 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"
176
The modern mode, "use strict"
Why Strict Mode?
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;
179
JavaScript Modules
2. Default Exports
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.
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
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
• Onmouseout() - The user moves the mouse away from an HTML element
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);
191
Browser Environment, Specifications
DOM (Document Object Model)
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.
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.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
<div id="headingDiv">
<h1 id="h1Tag">This is an h1 Tag</h1>
<h2 class="h2Tag">This is an h2 Tag</h2>
</div>
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.
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
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.
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
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()
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
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 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
Delete a Cookie
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.
216
Storing Data in JavaScript
Notes :
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.
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
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
.then(function(result){
//handle success
}, function(error){
//handle error
})
229
JavaScript Promises
2. Promise catch() Method
.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.
.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
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
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");
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
Note : You will have to generate your own <script> src link to
access the icons.
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, ...)
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
Declarations on Top
Initialize Variables
Avoid undefined values
Misunderstanding Floats
• All numbers in JavaScript are stored as 64-bits Floating point numbers (Floats).
252
JavaScript Performance
How to speed up your JavaScript code.
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.
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
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");
}
})
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