JavaScript Basics and ES6 Features
JavaScript Basics and ES6 Features
Uses
It is used to refresh the social media feeds and create the animations, create interactive maps,
create click to show dropdown menus and change element colours in the webpage.
User Interaction-:
- The user interacts with the prestation tier for example enter the data in the web form or
clicks the button.
Request Processing: -
- The presentation tier sends the user request to the application layer or tier
Business Logic: -
- The logic tier executes the relevant business logics, process the data and potentially interacts
with the database or data layer to retrieve or store the data.
Data Access:
- If necessary, the application tier communicates with the data tier to access the database.
- The logic tier formulates a response based on the process data and business rules and
packages it into the expected format that your presentation layer required.
Display:
- The presentation receives the response from the application tier and displays the
information to the user.
What is a JavaScript?
- JavaScript is high level programming language which is used to create interactive webpages
- It is the only language understood by the browser
- JavaScript is scripting language.
- It is a language you can use at a browser side as well as server side.
- It is most commonly and popular language used right now.
- Lot of framework and libraries based on JavaScript it can be used for both frontend and
backend.
o Ex: In frontend we use reactJs, angular js, nextJs.
o For backend we use NodeJS, expressJs.
Mocha
Live Script
JavaScript
May use prototypes or structures and often focus on practical use of inbuilt objects like math,
date rather than strict adherence of object-oriented principles.
JS Runtime Environment
Fetch BOM
Obj
Execution
1
Context
Time function DOM
Obj
Execution 2
Context Many More
Parser:
- This is the first stage of the engine every time we run a JavaScript program our code is
received by the parser inside the JS engine
- The parser job is to check the syntactic error in line-by-line manner and convert it into the
AST format (Abstract Structure Tree).
- Once the parser checks all the JavaScript code and get satisfied that there is no mistakes or
error in the code then it creates the data Abstract structure tree.
JIT Compiler:
- With the help of the Jit compiler we can convert into machine code language, once convert it
is given to the interpreter.
Interpreter:
Processor:
- The processor role in the JavaScript engine involves executing instruction generated by the
Engine whether they are interpreted byte code or Jit compile machine code.
Processor Interpreter
1. Web application
2. Web development
3. Mobile
4. Game developments
5. Presentation and slide shoe
6. Server application
7. Web servers
8. Client-side validations
9. Display pop-up windows and dialogue box
10. Animate elements
11. Dynamic Drop-down menu
Java JavaScript
Java is programming language JavaScript is scripting language
It is multi-threaded language It is single thread language
Java is strictly typed language It is loosely typed
It runs on JVM It runs on all the browser ex: chrome, brave
More Memory use in java It uses less memory
It is independent language Dependent on html
Browser Js Engine
Chrome V8 Engine
Fire fox Spider monkey
Safari JavaScript core
Internet Explorer Chakra
Brave V8+blink
Heap Memory:
- This is the place where all the object are stored which are necessary in the application.
Call Stack:
Execution Context:
- When the JavaScript code it executes within an execution context this context includes the
global context for code outside of the functions and function context for code inside the
functions.
- Each context has its own scope variable and functions.
• With the help of <script> tag we can embedded the java script code.
We wont use script tag in head section as when executing the html file initially head will
execute along with it js code also get executes which may cause some errors.
Defer:
It specifies that the script is download in parallel to parsing the page and the script executes after the
page has finished parsing.
If the user wants to write the script in the head, then the user needs to write defer so that the after
Note:
The defer attribute only for external scripts (should only be used only if src attribute present.
- we can create a separate file for JavaScript code with extension .js.
- Link the js file with html page using src attribute in side the opening of script tag.
Ex: [Link]
Tokens:
Tokens is a smallest unit of any programming language, there are various types of tokens in a
JavaScript.
1. Keyword
2. Identifier
3. Literal
4. Operator
5. Separator
6. Comment
1. Keywords:
keywords are the predefined words which haves some special meaning.
Keywords are always in lower case
It is understood by JavaScript.
Ex: var, let, const, async, break, continue, function.
2. Identifiers:
• Identifier is nothing but the name provided to any variable, class, function or
object.
Rules of identifiers:
1. You can’t use keywords as identifier.
2. Identifier name start with a number can have number between it.
3. It cannot have any special character expect underscore and $
4. It does not contain any space in between.
3. Literal:
- Literal is nothing but the data provided by the user.
Variables:
- Variable is nothing but name given to the block of memory.
- We can create a variable in java script using variable declaration followed by variable name.
- Syntax: variable_declaration variable_name=value;
- There are 3 types of variable declaration
1. Var
2. Let (added in ES6)
3. Const (added in ES6)
- Var A; →Declaration of a variable
- A=20; →Initialisation of a variable
- Var b = 30; → declaration and initialisation of variable
- A=40; → reinitialization
- Var A = 50; →Re declaration
1. Var:
- Var is the traditional way of declaring the variables.
- The var statement declare function scope or global scope variables optionally
initializing the value to the variable.
- It can be redeclare and updated within its scope.
- It can be declared without initialization.
- It can be accessed without initialization as its default value as undefined.
- It is a processing of accessing the variables before its initialization this will be possible only if
the variable is declared with the var type variable declaration.
- If any variable is declared with let or constant and trying to access that variable before its
initialization then the variable present in the temporal dead zone.
- And it returns an uncaught reference error.
- Def: It is a time interval between start of block and the point where a variable is declared
during this time the variable exists but cannot be accessed or used.
- Temporal Dead zone s only applied to variables declared with let and const.
Bare Declaration: **
Whenever we are declaring a variable without using var, let, const declarations then JS engine
automatically treats the declaration as Bare Declaration.
Bare declaration works only when the variable is not in any block or function i.e. it works only when
the variable is declared globally.
2. Let:
- The scope of let variable is the block scope.
- It can be updated but cannot be redeclared in the same scope.
- It can be declared without initialization.
- It cannot be accessed before initialization.
- If you are trying to access after the declaration without initialization, we will get
value as the undefined.
Scopes:
- scope is the area where a variable exist and accessable
1. Block Scope:
- Whenever we are declaring a variable with let, or const inside the curly braces is
known as block scope.
- Those variables that are declared inside the function have local or function scope
which means that we cannot access outside of the function.
2. Function Scope:
- Whenever we are declaring a variable with var, const or let then that particular
variable is under function scope.
- Those variables that are declared inside the function have local or function scope
which means that we cannot access outside of the function
Data Types:
- Data types are used to define what type of data we are going to store in a
particular variable.
- Data types are used to specify which type of value a variable can hold.
- They define the kind of data present inside the variable.
- JavaScript provides different data types to store the different types of values.
- There are 2 types of datatypes present in JS.
- JavaScript is a dynamically typed language which means you do not need to specify the type
of data that particular variable can hold. The type is determined at runtime based on the
value assigned to the variable
▪ Boolean
1. Java script Boolean represent true or false values
2. It is used for logical operations, conditional testing and variable
assignments based on conditions.
3. values like 0, Nan (not a number), Empty string (“”), undefined are the
falsie values.
4. Non empty strings other than 0, objects and array are truthy values.
Note: A falsie value is a value that is considered as false when
encountered in Boolean context.
▪ Undefined:
1. This means that a variable has been declare but has not been assigned a
value or it has been explicitly set to the value undefined.
▪ Big Int:
1. In JavaScript big int is the numeric datatype that can represent
integers in the arbitrary precession format. [no limit in range of
numbers]
2. Big int value is also known as big int primitive value which is created
by appending ‘n’ to an integer literal.
▪ Null:
1. Null is an empty value.
2. Null is not same as the zero.
3. Null is the absence of any value.
4. Ex: [Link] (null == undefined) //true
5. Ex: [Link] (null === undefined) // false
Type Coercion:
- Type coercion is also known as implicit type conversion.
- Implicit conversion:
It is used for some statement has to be executed based on the single condition.
Syntax:
if(condition)
{
//statements
if (cookiesAvaliable == 1)
If (cookiesAvaliable == 2) // error
Example:
- Note:
1.) The switch statement accepts n number of cases
2.) Cases are case-sensitive
3.) Default value has the least priority.
4.) The cases must be constant and unique.
5.) The cases cannot be variable or expression.
6.) The execution will flow through each case if break is missing in the satisfied case.
1) for loop:
- for loop it is used to execute set of statements repeatedly it is commonly
used when we know how many times the loop needs to be executed.
- Syntax:
for (initialization; condition; updation)
{
//set of statements
}
2) While loop:
- It loops through a block of code as long as specified condition is true.
- It commonly used when you don’t know how many times you want to
execute a block of code and it is based on the condition.
- Syntax:
Initialization
While(condition)
{
//statements
//updation
3) Do while loop:
- Do while loop will execute code of block once before checking the
condition.
- If the condition is true then it will repeat the loop as long as the
condition is true, and once condition is false it will stop the execution of
the block
- It is commonly used when you have to execute the loop at least once.
- Syntax:
Initialization
do
{
//statements
//updation
} while(condition);
let i=2;
do
{
[Link](i)
i+=2
} while(i<=100);
FUNCTIONS
- Reusable block of code that perform specific task.
- Define with function keyword, name, parameters (optional) and a body of code in curly
braces.
- Called by using the function name and passing the argument (optional)
- Syntax:
- function funcitonName (list of arguments)
{
//statements
}
functionName (list of arguments);
Example:
function sayHello(name)
{
[Link] (`Hello ${name}`)
}
sayHello("Dhanush");
Types of Functions:
- Example:
function mul (a, b)
{
[Link](a*b)
}
mul (10,20)
3.) Anonymous Function:
- A function declared without an identifier is known as anonymous function.
- To execute anonymous function, we have to store them into one variable.
- Syntax:
function ()
{
//body
}
- Example:
let a = () => {
[Link] ("This is arrow function")
}
- To execute this function, we need to store the function in the variable and we need
to invoke using that variable
4.) Function Expression
- Whenever we are storing any function into a variable then it is called as function
expression.
- Syntax:
var a = function ()
{
//body
}
a ();
- Example 1:
let a = () => {
[Link] ("This is arrow function")
}
a ();
- Example 2:
let even=function(num)
{
for (let i=2; i<=num; i+=2)
{
[Link](i)
}
}
even(num);
JAVASCRIPT NOTES BY SHIVA SIR 22
5.) First class function:
- It is a function which is assigned as a value to a variable.
- It can be a named function or anonymous function or arrow function.
- It can be accessed only with the variable name, you cannot access it with the
function name in case of named function
-
Ex:
Let a = () => {
}
Fat arrow
- Conciseness
- Readability
- This keyword binding.
(function () {
[Link] ("this is iikf 2")
})();
- Example 2:
(function () {
let secretMessage="Chocolate is in the freezer"
function showSecretMessage(secretMessage)
JAVASCRIPT NOTES BY SHIVA SIR 25
{
[Link](secretMessage)
}
showSecretMessage(secretMessage)
})();
- It is used to create a private scope encapsulate variables and functions and avoid
polluting the global name space.
- How it works:
o The function () part defines an anonymous function.
o Grouping Operator, the outer parenthesis groups the function expression.
o Immediate invocation the final pair of parentheses immediately invokes the
function
- Lexical Scope:
o Nested function inherits the scope of the outer function this means they can
access variables and parameters declared in the outer function.
o Example:
function createCounter()
{
let count=0;
function increaseCount()
JAVASCRIPT NOTES BY SHIVA SIR 26
{
count++;
return count
}
return increaseCount ();
}
let result=createCounter ()
[Link](result)
- Scope chaining:
- In JavaScript scope chaining refers to the hierarchical structure of scopes
that the JavaScript engine traverses to find the value of the variable or a
function.
- This chain starts from local scope and moves up to the global scope.
- Example:
let globalVariable="Global value"
function outerFunction () {
let outerVariable="Outervalue"
function innerFunction()
{
let innerVaribale="inner value"
[Link](innerVaribale, outerVariable,globalVariable)
}
innerFunction()
}
outerFunction () //inner value outer value global value
- Example Type-2:
function calculateRateOfIntrest(p)
{
return function(r) {
return function(t) {
return (p*t*r)/100
}
}
}
let SI=calculateRateOfIntrest (1000) (5)(2)
[Link] (SI)
- Curried functions are mostly used to create higher order functions.
- They can help in writing more concise and readable code.
- Using currying function, you can break down complex functions into simpler,
modular.
Arrays
1) An array in JavaScript is a data structure that stores a collection of elements.
2) These elements can be of various data types, including numbers, strings, objects, or even
other arrays.
3) Arrays are ordered, meaning each element has a specific index associated with it, starting
from 0.
Creating an Array:
1) Array Literal:
let myArray = [1, 2, 3, "hello", true];
This syntax directly initializes an array with the specified elements.
2) Using the Array constructor:
let myArray = new Array(5); // Creates an array with 5 empty elements
let myArray = new Array(1, 2, 3); // Creates an array with 3 elements
ex:
- You can modify elements of an array by assigning new values to their indices:
- myArray[2] = 10; // Changes the third element to 10
1.) push():
- Adds one or more elements to the end of an array.
- Syntax:
▪ [Link](element1, element2, ...);
- ex: const numbers = [1, 2, 3];
- [Link](4, 5); // numbers becomes [1, 2, 3, 4, 5]
- Return type: - new array length.
2.) pop():
- Example:
const numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
[Link](); // numbers becomes [1, 1, 2, 3, 3, 4, 5, 5, 5, 6,9]
- Return type: The modified array
11.) forEach():
- Executes a provided function once for each array element.
- syntax:
- [Link](callbackFunction);
- Example
const numbers = [1, 2, 3];
[Link](number => [Link](number));
- Return type: undefined.
12.) map():
- Creates a new array by transforming each element of the original array.
- Syntax:
- [Link](callbackFunction);
- Example:
const numbers = [1, 2, 3];
const doubledNumbers = [Link](number => number * 2); //
doubledNumbers is [2, 4, 6]
- Return type: A new array.
13.) filter():
- Creates a new array with elements that pass a test implemented by a provided
function.
- Syntax:
- [Link](callbackFunction);
JAVASCRIPT NOTES BY SHIVA SIR 31
- Example:
- const numbers = [1, 2, 3, 4, 5];
- const evenNumbers = [Link](number => number % 2 === 0); //
evenNumbers is [2, 4]
- Return type: A new array.
14.) reduce():
- Reduces an array to a single value.
- syntax:
- [Link](callbackFunction, initialValue);
- ex:
const numbers = [1, 2, 3];
const sum = [Link]((accumulator, currentValue) => accumulator +
currentValue, 0); // sum is 6
- Return type: A single value
15.) find():
- Returns the value of the first element in the array that satisfies the provided testing
function.
- syntax:
- [Link](callbackFunction);
- Example:
const numbers = [1, 2, 3, 4, 5];
const firstEvenNumber = [Link](number => number % 2 === 0); //
firstEvenNumber is 2
- Return type: The found element, or undefined if not found.
JavaScript Strings
In JavaScript we can create Strings in 4 ways:
1.) charAt():
- Syntax: [Link](index)
- Description: Returns the character at the specified index.
- Return Type: String
- Example:
15.) startsWith()
- Syntax: [Link](substring)
- Description: Checks if the string starts with the specified substring.
- Return Type: Boolean
- Example:
let website = 'Visit MicroSoft';
[Link]([Link]("Visit")); // true
16.) endsWith()
- Syntax: [Link](substring)
- Description: Checks if the string ends with the specified substring.
- Return Type: Boolean
- Example:
let website = 'Visit MicroSoft';
[Link]([Link]("Soft")); // true
17.) slice()
- Syntax: [Link](startIndex, endIndex)
- Description: Extracts a portion of the string based on specified indexes.
- Return Type: String
- Example:
let website = 'Visit MicroSoft';
[Link]([Link](6, 11)); // "Micro"
18.) split():
- Syntax: [Link](delimiter)
- Description: Splits the string into an array based on the specified delimiter.
- Return Type: Array
- Example:
let message = "How are you Shourya and someone";
[Link]([Link](" ")); // ["How", "are", "you", "Shourya", "and",
"someone"]
19.) search()
- Syntax: [Link](pattern)
- Description: Searches for a pattern and returns the index of its first occurrence.
- Return Type: Number
- Example:
let message = "How are YOU Shourya and someone";
[Link]([Link](/you/i)); // 8
- Keys can be written without quotes if they are valid JavaScript identifiers (e.g., name, age).
- Use quotes (single or double) for keys with spaces or special characters (e.g., "first name",
"age#").
- Keys are case-sensitive (e.g., name and Name are different).
Delete Operator:
delete [Link];
Methods in JavaScript:
1.) keys():
- Syntax:
[Link](obj)
- Description:
Returns an array of the object’s own enumerable property names.
- Return Type: Array
- Example:
let user = {
name: "Shourya",
age: 23,
city: "Cyberabad"
};
let keys = [Link](user);
[Link](keys); // ["name", "age", "city"]
for (let i = 0; i < [Link]; i++) {
[Link](user[keys[i]]); // Accessing values using keys
}
2.) values():
- Syntax:
[Link](obj);
- Description:
Returns an array of the object’s own enumerable property values.
- Return type: Array
- Example:
let user = {
name: "Shourya",
age: 23,
city: "Cyberabad"
};
let values = [Link](user);
[Link](values); // ["Shourya", 23, "Cyberabad"]
3.) Entries():
- Syntax: [Link](obj)
[Link](); // Eating...
[Link](); // Barking...
// Strict mode
"use strict";
[Link](this); // undefined
2. Inside a Function:
- Non-Strict Mode: Refers to the global object.
- Strict Mode: this is undefined
// Non-strict mode
function myFunction() {
[Link](this); // window
}
myFunction();
// Strict mode
"use strict";
function myStrictFunction() {
[Link](this); // undefined
}
myStrictFunction();
3. Inside a Method (Object Context):
- In arrow functions, the `this` keyword is lexically bound, meaning it inherits `this`
from the surrounding (non-arrow) function or the global context where the arrow
function is defined
- Example:
function outerFunction() {
const arrowFunc = () => [Link](this); // Inherits `this` from the
enclosing function
arrowFunc();
}
outerFunction();
const obj = {
name: "Raj",
getName: () => {
[Link]([Link]); // `this` here depends on the outer context (likely
`undefined` or `window`).
},
};
[Link]()
- This keyword inside a method refers to the object that the method is a part of
JSON Object:
1.) JSON means JAVASCRIPT OBJECT NOTATION
2.) JSON is a light weight, text-based data interchange format that is easy for humans to read
and write and easy for machines to parse and generate
3.) It is derived from syntax of JS object literals.
uses of JSON:
OR
Asynchronous JavaScript allows the execution of tasks without blocking the main thread. This non-
blocking nature enables JavaScript to perform other tasks while waiting for long-running operations
to complete, improving efficiency and user experience.
1.) Non-Blocking:
- Asynchronous code lets other tasks run while waiting for operations like network
requests to complete.
2.) Concurrency:
- JavaScript uses the event loop to manage tasks, making it feel like multiple tasks run
at the same time, even though it's single-threaded.
3.) Improved Performance:
- Multiple tasks can be handled without slowing down or freezing the user interface.
<script>
let timeoutId;
function start() {
timeoutId=setTimeout(()=>{
[Link]("<h1>Hello set timeout</h1>")
},3000)
}
function stop() {
clearTimeout(timeoutId);
alert("time out stopped")
}
</script>
- Real world Use Cases:
1. Cancel a Task on User Action:
Example: Cancelling a notification or warning when the user responds
quickly.
2. Prevent Duplicate Actions:
Example: Clearing a timeout to debounce user inputs or clicks.
iii. setInterval():
- The setInterval function in JavaScript is commonly used for repeating a task
at fixed intervals.
- Syntax:
setInterval(callback, delay, arg1, arg2, ...);
1. callback: The function to be executed repeatedly.
2. delay: The time interval (in milliseconds) between each execution.
3. arg1, arg2, ...: (Optional) Arguments to pass to the callback function.
- it will return a numeric interval ID, which can be used with clearInterval() to
stop the repeated execution.
- Example:
setInterval(() => {
const now = new Date();
[Link]([Link]());
}, 1000);
iv. clearInterval():
- The clearTimeout() function in javascript clears the timeout which has been
set by the setTimeout()function before that.
- Syntax:
clearInterval(intervalId);
JAVASCRIPT NOTES BY SHIVA SIR 48
- Example:
let counter = 0;
const intervalID = setInterval(() => {
[Link](counter);
counter++;
if (counter === 5) {
clearInterval(intervalID);
[Link]("Interval cleared.");
}
}, 1000);
[Link]=function () {
[Link]("Request failed")
}
Promise
- The Promise is an object represents the eventual completion (or failure) of an
asynchronous operation and its resulting value.
- A promise object has a state that can be one of the following:
1.) Pending
2.) Fulfilled with a value
3.) Rejected for a reason
- In the beginning, the state of a promise is pending, indicating that the asynchronous
operation is in progress.
- Depending on the result of the asynchronous operation, the state changes to either
fulfilled or rejected.
- The fulfilled state indicates that the asynchronous operation was completed successfully:
- The rejected state indicates that the asynchronous operation failed.
// contain an operation
if (success) {
resolve(value);
}
else {
reject(error);
}
});
- The promise constructor accepts a callback function that typically performs an
asynchronous operation. This function is called as an executor function.
- The executor function accepts two callback functions with the name resolve and
reject.
function onFulfilled(users) {
[Link](users);
}
function onRejected(error) {
[Link](error);
function getUsers() {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (success) {
resolve([
{ username: 'john', email: 'john@[Link]'
},
{ username: 'jane', email: 'jane@[Link]'
},
]);
}
else {
reject('Failed to the user list');
}
}, 1000);
});
}
[Link]((error) => {
[Link](error);
});
3.) The finally() method:
- Sometimes, you want to execute the same piece of code whether the promise is
fulfilled or rejected.
- Syntax:
[Link](callbackfun)
const render = () => {
//...
};
getUsers()
.then((users) => {
Promise Chaining:
- Sometimes, you want to execute two or more related asynchronous operations, where the
next operation starts with the result from the previous one.
- Promise chaining is a programming pattern in JavaScript used to handle sequences of
asynchronous operations where each subsequent operation starts only after the previous
one completes.
- This is done by chaining .then() handlers to a promise.
- Each .then() returns a new promise, allowing subsequent .then() calls to form a chain.
- Syntax:
step1().then(result => step2(result)).then(result => step3(result))...
- Example:
let p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(10);
}, 3 * 100);
});
[Link]((result) => {
[Link](result);
return result * 2;
});
- The callback passed to the then() method executes once the promise is resolved. In the
callback, we show the result of the promise and return a new value multiplied by two
(result*2).
- Because the then() method returns a new Promise with a value resolved to a value, you can
call the then() method on the return Promise like this.
let p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(10);
}, 3 * 100);
});
[Link]((result) => {
[Link](result);
return result * 2;
}).then((result) => {
[Link](result);
Returning a Promise:
- When you return a value in the then() method, the then() method returns a new Promise
that immediately resolves to the return value.
Promise Methods:
1.) [Link]():
- The [Link]() method returns a single promise that resolves when all the input promises
have been resolved.
- The [Link]() static method takes an iterable of promises:
- Syntax: [Link](iterable);
- In other words, the [Link]() waits for all the input promises to resolve and returns a
new promise that resolves to an array containing the results of the input promises.
- If one of the input promises is rejected, the [Link]() method immediately returns a
promise that is rejected with an error of the first rejected promise:
- Example
1) Resolved promises example:
[Link](`Results: ${results}`);
});
const p2 = new Promise((resolve, reject) => {
setTimeout(() => {
[Link]('The second promise has rejected');
reject('Failed');
}, 2 * 1000);
});
const p3 = new Promise((resolve, reject) => {
setTimeout(() => {
[Link]('The third promise has resolved');
resolve(30);
}, 3 * 1000);
});
2.) [Link]():
- If one of the promises in the iterable object is fulfilled, the [Link]() returns a
single promise that resolves to a value which is the result of the fulfilled promise.
- The [Link]() method accepts a list of Promise objects as an iterable object.
- syntax:
[Link](iterable);
- The [Link]() returns a promise that is fulfilled with any first fulfilled promise
even if some promises in the iterable object are rejected:
- Example:
const p1 = new Promise((resolve, reject) => {
setTimeout(() => {
[Link]('Promise 1 fulfilled');
JAVASCRIPT NOTES BY SHIVA SIR 55
resolve(1);
}, 1000);
});
- ES2017 introduced the async/await keywords that build on top of promises, allowing you to
write asynchronous code that looks more like synchronous code and is more readable.
- Technically speaking, the async / await is syntactic sugar for promises.
async Keyword:
- The async keyword allows you to define a function that handles asynchronous
operations.
- To define an async function, you place the async keyword in front of the function
keyword as follows:
- Asynchronous functions execute asynchronously via the event loop. It always returns a
Promise.
- Example:
async function sayHi() {
return 'Hi';
}
- In this example, because the sayHi() function returns a Promise, you can
consume it, like this:
sayHi().then([Link]);
- You can also explicitly return a Promise from the sayHi() function as shown
in the following code:
async function sayHi() {
return [Link]('Hi');
}
await keyword:
- You use the await keyword to wait for a Promise to settle either in a resolved or
rejected state.
- You can use the await keyword only inside an async function.
async function:
- Represents the browser window and serves as the global object in JavaScript.
- The Browser Object Model (BOM) in JavaScript is a collection of objects that allows developers to
interact with the web browser.
- It provides functionalities to manipulate the browser window, history, navigation, and other aspects
of the browser environment.
- whenever we are running the application then browser creates Web Api (Provided by browser).
- The global object of JavaScript in the web browser is the window object.
- It means that all variables and functions declared globally with the var keyword
become the properties and methods of the window object.
- The window object exposes the functionality of the web browser to the webpage.
1.) alert():
- The browser can invoke a system dialog to display information to the user.
- To invoke an alert system dialog, you invoke the alert() method of the window object.
- The alert() is a method of the window object.
- The alert() method is modal and synchronous.
- Use the alert() method to display information that you want users to acknowledge.
- Syntax:
[Link](message);
OR
alert(message);
- The message is a string that contains information that you want to show to users.
- Example:
[Link]('Welcome to [Link]!');
OR
alert('Welcome to Browser Object Model');
- When the alert() method is invoked, a system dialog shows the specified message to
the user followed by a single OK button.
- Note : the alert dialog is synchronous and modal. It means that the code execution
stops when a dialog is displayed and resumes after it has been dismissed.
2.) confirm():
- The confirm() is a method of the window object.
- The confirm() shows a system dialog that consists of a question and two buttons: OK
and Cancel.
- The confirm() returns true if the OK button was clicked or false if the Cancel button
was selected.
- Syntax:
let result = [Link](question);
- In this syntax:
1. The question is an optional string to display in the dialog.
2. The result is a Boolean value indicating whether the OK or Cancel button
was clicked. If the OK button is clicked, the result is true; otherwise, the
result is false.
- The confirmation dialog is modal and synchronous. It means that the code execution
stops when a dialog is displayed and resumes after it has been dismissed.
- Example:
let result = confirm('Are you sure you want to delete?');
let message =result ? 'You clicked the OK button' :'You clicked the Cancel
button';
alert(message);
3.) Window Size:
- The window object has four properties related to the size of the window.
- 1. innerWidth and innerHeight:
Location Object:
1. [Link]:
Node:
- A node refers to any of the various parts that make up the structure of a document.
- Every element, attribute, and piece of text in a webpage is represented as a node.
- There are different types of nodes in the DOM.
Types of Nodes:
Hierarchy in DOM:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<div id="main">
<p>Hello, World!</p>
JAVASCRIPT NOTES BY SHIVA SIR 61
</div>
</body>
</html>
1. [Link]:
- Returns a collection (similar to an array) of all elements in the document.
- Syntax:
[Link]
- Example:
[Link]([Link][0]); // Logs the first element in the document.
2. [Link]:
- Returns an HTMLCollections of all <script> elements in the documents.
- Synatx:
[Link]
- Example:
[Link]([Link]); // Logs the number of scripts in the
document.
3. [Link]:
- Returns an HTMLCollections of all <img> elements in the document.
- Syntax:
[Link]
- Example:
4. [Link]:
- Returns an HTMLCollection of all <a> elements with an href attribute in the document.
- syntax:
[Link]
- Example:
[Link]([Link][0].href); // Logs the URL of the first
5. [Link]:
- Returns an HTMLCollection of all <form> elements in the document.
- Syntax:
[Link]
6. [Link]:
1. getElementById() :
- The [Link]() returns a DOM element specified by an id or null if no
matching element is found.
- If multiple elements have the same id, even though it is invalid, the getElementById() returns
the first element it encounters.
- Syntax:
const element = [Link](id);
- In this syntax:
id is a string that represents the id of the element to select.
- Note: the method matches ID case-sensitively. For example, the 'root' and 'Root' are
different.
- If the document has no element with the specified id, the getElementById() method returns
null.
2. getElementsByName():
- The getElementsByName() accepts a name which is the value of the name attribute of
elements and returns a NodeList of elements.
- Every element on an HTML document may have a name attribute.
- The NodeList is an array-like object, not an array object.
- Syntax:
let elements = [Link](name);
- Example:
<input type="radio" name="language" value="JavaScript">
<input type="radio" name="language" value="JavaScript">
let elements = [Link](language);
3. getElementsByClassName():
- The getElementsByClassName() method returns an HTMLCollection of elements whose class
names match one or more specified class names.
- Syntax:
getElementsByClassName(names).
- In this syntax:
names represent one or more class names to match. If you use multiple class
names, you need to separate them by a space
- Travesing Elements.
- The getElementsByClassName() method returns a HTMLCollection of the matched elements.
- If no element in the document matches the class names, the getElementsByClassName()
method returns an empty HTMLCollection [].
- Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
JAVASCRIPT NOTES BY SHIVA SIR 63
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript getElementsByClassName</title>
</head>
<body>
<header>
<nav>
<ul id="menu">
<li class="item">HTML</li>
<li class="item">CSS</li>
<li class="item highlight">JavaScript</li>
<li class="item">TypeScript</li>
</ul>
</nav>
<h1>getElementsByClassName Demo</h1>
</header>
<section>
<article>
<h2 class="secondary">Example 1</h2>
</article>
<article>
<h2 class="secondary">Example 2</h2>
</article>
</section>
</body>
</html>
1. parentNode:
- To get the parent node of a specified node in the DOM tree, you use the parentNode
property:
- let parent = [Link];
- The parentNode is read-only.
- The Document and DocumentFragment nodes do not have a parent. Therefore, the
parentNode will always be null.
- If you create a new node but haven’t attached it to the DOM tree, the parentNode of
that node will also be null.
- The [Link] returns the read-only parent node of a specified node or null if it
does not exist.
- Example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript parentNode</title>
</head>
<body>
<div id="main">
<p class="para">This is a note!</p>
</div>
<script>
let note = [Link]('#para');
[Link]([Link]);
</script>
</body>
</html>
- How it works:
1. Select the element with the .note class by using the querySelector() method.
2. Find the parent node of the element.
MCQ’S:
ans: a
Q.2 Given the HTML <div id='parent'><p id='child'>Hello</p></div>, how can you access the parent
element of the paragraph?
a. [Link]('parent').parentNode
b. [Link]('child').parentNode
c. [Link]('child').childNode
d. [Link]('parent').childNode
ans: b
a. null
ans: b
Q.4 If an element does not have a parent node, what will the parentNode property return?
a. null
b. undefined
d. An error
ans: a
Q.5 How can you check if an element has a parent node in JavaScript?
a. if ([Link] != null)
b. if ([Link] == element)
c. if ([Link] > 0)
2. Siblings of an Element:
1. nextElementSibling:
- To get the next sibling of an element, you use the nextElementSibling
- let nextSibling = [Link];
- The nextElementSibling returns null if the specified element is the last one in the list.
- Example:
<ul id="menu">
<li>Home</li>
<li>Products</li>
<li class="current">Customer Support</li>
<li>Careers</li>
<li>Investors</li>
<li>News</li>
<li>About Us</li>
</ul>
let current = [Link]('.current');
let nextSibling = [Link];
[Link](nextSibling);
- How it works:
[Link] the list item whose class is current using selecting method.
[Link] the next sibling of that list item using the nextElementSibling property.
- Q. How to get all the next siblings of an element:
let current = [Link]('.current');
let nextSibling = [Link];
while(nextSibling) {
[Link](nextSibling);
nextSibling = [Link];
}
2. nextSibling:
- Returns the next sibling node of any type, including text nodes, comment nodes, and
element nodes.
- If there are no sibling nodes after the specified one (like when it's the last one), it
returns null.
- Example:
<div id="first">First</div>
<!-- This is a comment -->
<div id="second">Second</div>
<script>
const firstDiv = [Link]('first');
[Link]([Link]);
</script>
3. previousElementSibling:
JAVASCRIPT NOTES BY SHIVA SIR 67
- To get the previous siblings of an element, you use the previousElementSibling.
- let current = [Link]('.current');
let prevSibling = [Link];
- The previousElementSibling property returns null if the current element is the first
one in the list.
4. Previoussibilings:
- The previousSibling property returns the previous sibling node of the specified node,
which could be any type of node (text, comment, element, etc.).
- If there is no previous sibling node, it returns null.
- Example:
<div id="first">First</div>
<!-- This is a comment -->
<div id="second">Second</div>
<script>
const secondDiv = [Link]('second');
[Link]([Link]); // Logs the comment node
</script>
1. firstChild:
- To get the first child element of a specified element, you use the firstChild
- If the parentElement does not have any child element, the firstChild returns null.
- The firstChild property returns a child node which can be any node type such as an
element node, a text node, or a comment node.
- Example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Get Child Elements</title>
</head>
<body>
<ul id="menu">
<li class="first">Home</li>
<li>Products</li>
<li class="current">Customer Support</li>
<li>Careers</li>
<li>Investors</li>
<li>News</li>
<li class="last">About Us</li>
</ul>
</body>
</html>
- The following script shows the first child of the #menu element:
let content = [Link]('menu');
let firstChild = [Link];
[Link](firstChild);
2. firstElementChild:
JAVASCRIPT NOTES BY SHIVA SIR 68
- to get the first child with the Element node only.
- let firstElementChild = [Link];
- Example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Get Child Elements</title>
</head>
<body>
<ul id="menu">
<li class="first">Home</li>
<li>Products</li>
<li class="current">Customer Support</li>
<li>Careers</li>
<li>Investors</li>
<li>News</li>
<li class="last">About Us</li>
</ul>
</body>
</html>
- The following code returns the first list item which is the first child element of the.
let content = [Link]('menu');
[Link]([Link]); // <li class="first">Home</li>
- How it works:
In this example:
1. select the #menu element by using the getElementById() method.
2. get the first child element by using the firstElementChild property.
3. lastChild:
- To get the last child element of a node, you use the lastChild property:
let lastChild = [Link];
- In case the parentElement does not have any child element, the lastChild returns
null.
- The lastChild property returns the last element node, text node, or comment node.
- Note: If you want to select only the last child element with the element node type,
you use the lastElementChild property:
4. lastElementChild():
- If you want to select only the last child element with the element node.
- let lastChild = [Link];
- Example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Get Child Elements</title>
1. textContent():
- To get the text content of a node and its descendants, you use the textContent.
- The textcontent will give content how you writing in your html document.
- Syntax:
let text = [Link];
- Example:
<div id="note">
JavaScript textContent Demo!
<span style="display:none">Hidden Text!</span>
<!-- my comment -->
</div>
- The following example uses the textContent property to get the text of the <div>
element.
let note = [Link]('note');
[Link]([Link]);
output:
JavaScript textContent Demo!
Hidden Text!
- How it works:
1. First, select the div element with the id note by using the getElementById()
method.
2. Then, display the text of the node by accessing the textContent property.
2. innerText():
- innerText retrieves or sets the visible text content of an element, excluding any
hidden elements.
- Syntax: let textContent = [Link];
- Example
<div id="note">
5. appendChild():
- The appendChild() method allows you to add a node to the end of the list of child
nodes of a specified parent node.
- Syntax:
[Link](childNode);
classList:
6. toggle() method:
- If the class list of an element contains a specified class name, the toggle() method
removes it.
- If the class list doesn’t contain the class name, the toggle() method adds it to the
class list.
- syntax:
[Link]("className")
- Example:
let div = [Link]('#content');
[Link]('visible');
1. The element’s classList property returns the live collection of CSS classes of the element.
2. Use the add() and remove() methods to add CSS classes to and remove CSS classes from the
class list of an element.
3. Use the replace() method to replace an existing class with a new one.
4. Use the contains() method to check if the class list of an element contains a specified class.
5. Use the toggle() method to toggle a class.
Event Handling:
- Event handling refers to the process of writing code to detect and respond to events
triggered by the user or the browser.
- Event handling is achieved by attaching event listeners to elements in the DOM.
- These listeners "listen" for specific events and execute a predefined function, called
an event handler, when the event occurs.
1. Identify the type of event you want to handle (e.g., click, keypress, submit).
2. Attach an event listener: Use JavaScript to link the event to a specific function (the event
handler).
3. Respond to the event: Define what should happen when the event occurs.
- To define a function that will be executed when the button is clicked, you need to
register an event handler using the addEventListener() method.
- The addEventListener() method accepts three arguments: an event name, an event
handler function, and a Boolean value that instructs the method to call the event
handler during the capture phase (true) or during the bubble phase (false).
- Syntax:
[Link](event, function, useCapture);
- In this Syntax
[Link]: A string representing the name of the event (e.g., "click",
"mouseover", "keydown", etc.).
[Link]: The event handler function to execute when the event occurs. This
can also be an anonymous function or an arrow function.
[Link] (optional): A boolean indicating whether the event should be
captured during the capturing phase (true) or the bubbling phase (false).
- Defaults to false.
- Example:
let btn = [Link]('#btn');
[Link]('click', function(event) {
alert([Link]); // click
});
- It is possible to add multiple event handlers to handle a single event.
- Example:
let btn = [Link]('#btn');
[Link]('click',function(event) {
alert([Link]); // click
});
[Link]('click',function(event) {
alert('Clicked!');
});
- The removeEventListener() removes an event listener that was added via the
addEventListener().you need to pass the same arguments as were passed to the
addEventListener().
- Syntax:
- [Link](event, listener, options);
- In this syntax:
[Link]: The name of the event to remove, such as "click", "keydown", or
"resize".
[Link]: The event handler function that was previously added with
addEventListener. This must be the exact same function reference.
[Link] (Optional): An object or boolean indicating options such as capture. It
must match the options used in addEventListener
- Example:
let btn = [Link]('#btn');
// add the event listener
let handleClick = function() {
alert('Clicked!');
};
[Link]('click', handleClick);
// remove the event listener
[Link]('click', handleClick);
Event Propagation
- Event Propagation determines in which order the elements receive the event.
- Propagation refers to how events travel through the Document Object Model (DOM)
tree
- Bubbling and Capturing are the two phases of propagation.
Event bubbling:
- In the event bubbling model, an event starts at the most specific element and then
flows upward toward the least specific element (the document or even window).
- bubbling travels from the target element to the root.
- The target is the DOM node on which you click, or trigger with any other event.
- By default, most events use the bubbling phase when you add an event listener
without specifying the third argument:
- For example, a button with a click event would be the event target. The root is the
highest-level parent of the target. This is usually the document, which is a parent of
the, which is a (possibly distant) parent of your target element.
Event Capturing:
- It is the opposite of bubbling. The event handler is first on its parent component and
then on the component where it was actually wanted to fire that event handler.
- In short, it means that the event is first captured by the outermost element and
propagated to the inner elements.
- Capturing travels from the root to the target.
- Example:
<div id="parent">
<button id="child">Click Me!</button>
</div>
let ElementDiv = [Link]("parent");
let EventButton = [Link]("child");
ElementDiv .addEventListener("click", function() {
alert("Parent Div Clicked!");
},{ capture: true });
[Link]("click", function(event) {
alert("Button Clicked!")
},{ capture: true });
addEventListener():
stopPropagation():
- It will prevent further propagation through the DOM tree, and only run the event
handler from which it was called.
- Example:
function first() {
[Link](1);
}
function second() {
[Link](2);
}
var button = [Link]("button");
var container = [Link]("container");
[Link]("click", first);
[Link]("click", second);
- In the above example, clicking the button will cause the console to print 1, 2. If we
wanted to modify this so that only the button’s click
- Event is triggered, we could use [Link]() to immediately stop the
event from bubbling to its parent.
function first(event) {
[Link]();
[Link](1);
}
- This modification will allow the console to print 1, but it will end the event chain
right away, preventing it from reaching 2.
preventDefault():
- To prevent the default behavior of an event, you use the preventDefault() method.
- For example, when you click a link, the browser navigates you to the URL specified in
the href attribute.
- <a href="[Link]
- You can prevent this behavior by using the preventDefault() method of the event
object.
let link = [Link]('a');
[Link]('click',function(event) {
[Link]('clicked');
[Link]();
});
Event Delegation:
1. Mouse Events
2. Keyboard Events
1. Mouse Events:
- Mouse events fire when you use the mouse to interact with the elements on the
page.
- mousedown, mouseup, and click events:
- When you click an element, there are no less than three mouse events fire in the
following sequence:
- The mousedown fires when you press the mouse button on the element.
- The mouseup fires when you release the mouse button on the element.
- The click fires when one mousedown and one mouseup detected on the element.
dbclick event:
mousemove:
- The mousemove event fires repeatedly whenever you move the mouse cursor
around an element.
- This mousemove event fires many times per second as the mouse is moved around,
even if it is just by one pixel.
mouseout:
- The mouseout fires when the mouse cursor is over an element and then moves
another element.
mouseenter:
- The mouseenter fires when the mouse cursor is outside of an element and then
moves inside the boundaries of the element.
mouseleave:
- The mouseleave fires when the mouse cursor is over an element and then moves to
the outside of the element’s boundaries.
2. Keyboard Events:
- When you interact with the keyboard, the keyboard events are fired.
keydown:
- fires when you press a key on the keyboard and fires repeatedly while you’re holding
down the key.
- Example:
<style>
body {
<script>
const box = [Link]('box');
let topPosition = 100;
let leftPosition = 100;
[Link]('keydown', (event) => {
const step = 10;
switch ([Link]) {
case 'ArrowUp':
topPosition -= step;
break;
case 'ArrowDown':
topPosition += step;
break;
case 'ArrowLeft':
leftPosition -= step;
break;
case 'ArrowRight':
leftPosition += step;
break;
}
[Link] = `${topPosition}px`;
[Link] = `${leftPosition}px`;
});
</script>
JAVASCRIPT NOTES BY SHIVA SIR 83
</body>
</html>
keyup:
[Link]('keyup', () => {
[Link] = [Link];
});
keypress:
- Fires when you press a character keyboard like a,b, or c, not the left arrow key,
home, or end keyboard.
- The keypress also fires repeatedly while you hold down the key on the keyboard.
- Example:
<h1>Press any key to see the output in the console!</h1>
<script>
[Link]("keydown", function (event) {
[Link](`Key pressed: ${[Link]}`);
});
</script>
- ES6 provides a new kind of parameter so-called rest parameter that has a prefix of
three dots (...).
- A rest parameter allows you to represent an indefinite number of arguments as an
array.
- Example:
function fn(a,b,...args) {
[Link](args);
}
- The last parameter (args) is prefixed with the three dots ( ...). It’s called a rest
parameter ( ...args).
- All the arguments you pass to the function will map to the parameter list. In the
syntax above, the first argument maps to a, the second one maps to b, and the third,
the fourth, etc., will be stored in the rest parameter args as an array.
fn(1, 2, 3, "A", "B", "C");
- The args array stores the following values:
[3,'A','B','C']
- If you pass only the first two parameters, the rest parameter will be an empty array:
fn(1,2);
- The args will be [].
Spread operator:
- ES6 provides a new operator called spread operator that consists of three dots (...).
- The spread operator allows you to spread out elements of an object.
- The spread operator is denoted by three dots (...).
- The spread operator can be used to clone an iterable object or merge iterable
objects into one.
- Example:
const odd = [1,3,5];
const combined = [2,4,6, ...odd];
[Link](combined); //[ 2, 4, 6, 1, 3, 5 ]
- In this example, the three dots ( ...) located in front of the odd array is the spread
operator. The spread operator (...) unpacks
- The elements of the odd array.
Modules
- In JavaScript, a module is a file that contains code that can be imported into other code files.
- With the help of modules, developers can create more modular and scalable applications,
improving overall code quality.
- The import and export keywords serve as the bridge that connects different modules.
- The export keyword makes variables or functions available to other modules.
- The import keyword is utilized for importing variables or functions into other modules.
Types of Modules:
1. Common Js Modules
2. Es6 Modules
// file: [Link]
import { add, subtract } from './demo';
[Link](add(2, 3));
[Link](subtract(5, 2));
- Combining Imports: If you want, you can import multiple named exports
in one statement.
- Ex:2 // file: [Link]
const name="Raj"
const age=27
function sayHello(){
[Link]("Hello");
}
export {name,age,sayHello}
// file: [Link]
import {name, isSuperman} from './demo'
- Note : you can import all named exports at once using the asterisk (*) .
import * as newlyImport from './demo'
2. Export Default Module:
- Allows you to export one default item per module, and the importing
module can name it anything.
- You have to export default keywords.
- Example:
// file: [Link]
export default function divide(a, b) {
return a / b;
JAVASCRIPT NOTES BY SHIVA SIR 87
}
// file: [Link]
import divide from './demo';
[Link](divide(10, 2)); // Output: 5