Introduction to JavaScript Basics
Introduction to JavaScript Basics
❖ Introduction to JavaScript:
1. What is JavaScript?
● JavaScript is a high-level scripting as well as programming
language which is used to create interactive web pages.
● JavaScript is an object-based scripting language which is
lightweight and cross-platform
● With the help of JS we can able to add functionality and
behaviour to HTML and CSS webpages.
● It is the only language which is understood by the browser.
● JavaScript is also known as the scripting language
● A lot of framework and libraries are based on javascript. It
can be used for both frontend and backend.
1) Frontend → [Link], [Link], [Link], etc
2) Backend → [Link], [Link], etc
2. History of JS
1) Early Web Limitations :
● In the early days of the web, HTML and CSS were used to create
static web pages.
● HTML provided the structure, and CSS controlled the presentation.
● There was no way to create interactive or dynamic behavior
directly in the browser.
● Users had to reload entire pages to see updates or interact with
content, which was a significant limitation.
2) Creation of JavaScript :
● 1993 ⇒ Mosaic , the first popular web browser with a
graphical user interface, was released. It made the web
accessible to non-technical people and spurred the rapid
growth of the World Wide Web
● 1994 ⇒ The lead developers of Mosaic founded Netscape
Corporation and released Netscape Navigator , a more
polished browser.
● 1994 ⇒ The lead developers of Mosaic founded Netscape
Corporation and released Netscape Navigator , a more
polished browser.
● They collaborated with Brendan Eich to create JavaScript
● Early 1995 ⇒ The scripting language was initially called
"Mocha”
● September 1995 ⇒ Renamed "LiveScript” .
● December 1995 ⇒ Final name, "JavaScript" , was used in
Netscape Navigator 2.0.
3)ECMA
● ECMA (European Computer Manufacturers Association) , now
known as ECMA International, is an organization that develops
and publishes technical standards.
● Its role in the development of JavaScript is critical due to the need
for standardization across different web browsers.
● Since 2015, major versions have been published every June .
● ECMAScript 2024, the 15th and current version, was released in
June 2024.
● ES6 (released in 2015) → Major changes such as the addition of
arrow functions, template literals, and the let and const variable
declarations.
● ECMAScript continues to evolve and new versions are planned to
be released every year in the month of June, with new features
and improvements
● Present version is ECMA15
4)Characteristics of JS
● Light-weight Scripting Language → It’s easy to use and doesn’t
need much memory or processing power.
● Dynamic typing / Dynamically typed language →the type will be
not be specified in js
● Interpreted Language → JavaScript is primarily an interpreted
language, meaning it is executed line-by-line by the browser or
runtime environment without requiring a separate compilation step.
● Run in Browsers and Servers → Works both in web browsers and
on servers using tools like [Link]. Originally developed for client-
side scripting in web browsers, JavaScript can now also run on
servers using environments like [Link].
Working of JS Engine
[Link] Setup
● Where we can run js code?
➢ VS Code
➢ Node JS
Ways to Add JS
● Javascript Inside the tag
➢ You can also include JavaScript inside the tag of the HTML
file.
➢ Placing JavaScript within the section of an HTML document
ensures that the script is loaded and executed as the page
loads.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script >
[Link]('====================================');
[Link](hello);
[Link]('====================================');
</script>
</body>
</html>
● External Javascript:
➢ You can write JavaScript code in a separate file (e.g.,
[Link] ) and link it to the HTML file using the <script>
tag with a src attribute.
Example:<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="./[Link]"></script>
</body>
</html>
Fundamentals of JS
1. Tokens
Tokens are the smallest unit of any programming language that
can be understood by Javascript. When Javascript is interpreted,
the browser parses the script into these tokens.
JavaScript tokens fit in categories:
1. Keywords
2. Identifiers
3. Literals
● Keywords:
Keywords are predefined reserved words in any
programming language.
● .Literals :
➢ Literals are data used to represent fixed values in
JavaScript.
➢ These are fixed values directly written into the code.
➢ Integer Literals → Integers can be expressed in either
decimal
➢ Floating-Point Literals → Floating-point literals represent
decimal numbers
➢ Boolean Literals → JavaScript implements Boolean data
types
➢ Object Literals → Object literals in JavaScript are a way to
create objects
➢ . Array Literals → Array literals in JavaScript are a way to
create Array
JS Variables
● A javascript variable is simply the name of the storage
location.
● They are container for storing data.
● Variable is nothing but the container, where we can store the
value or data.
2. let ⇒
● The let statement is used to declare block-scoped variables,
meaning the variable is accessible only within the block in which it
is defined.
● Features → 1. Variables can be updated but cannot be re-
declared in the same scope.
2. Can be declared without initialization.
3. Cannot be accessed before initialization; attempting to do so
results in a ReferenceError ( Temporal Dead Zone ).
4. Variables declared with let are hoisted, but remain in the
Temporal Dead Zone until initialization.
● Const⇒ The const statement declares block-scoped variables that
` cannot be updated or re-declared.
Features →
1. Variables must be initialized during declaration.
2. Variables cannot be updated or re-declared in the same scope.
3. Cannot be accessed before initialization; attempting to do so
results in a ReferenceError (Temporal Dead Zone).
4. Variables declared with const are hoisted, but remain in the
Temporal Dead Zone until initialization.
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.
3. Script Scope: - When we are declaring a variable with let or const
outside the function and curly braces then that particular variable is
under script scope.
4. Global Scope: - Whenever we are declaring a variable with var type
declaration outside of the function and this variable is stored inside the
window object then we are calling this variable under the global scope.
- Those variables which are declare outside of the function are inside the
global scope. - In JavaScript global variable can be accessed from
anywhere.
Data Types:
- 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 .
1. Primitive Data Types - In JavaScript primitive datatype is the data
that is not an object and has no methods or properties. - The primitive
datatypes are single value
Number:
➢ Number datatype can use decimal as well as non-decimal values.
➢ Ex: var a = 10;
let myage=22;
String: -
The string datatype in the JavaScript represents a sequence of
characters that are surrounded by single or double quotes and template
literals (`Dhanush`)
- Typically, it is used to represent the text.
- Ex: var fname=” Dhanush”
- Var lname = ‘Pagolu’
- Var fullname=`full name is ${fname} ${lname}`
▪ 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.
2. let a = undefined
3. [Link](a); //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 conversion:
- In JavaScript type conversion is the process of changing the value of
one data type to another datatype.
- It is essential for performing operations and comparisons between
different datatypes
- Explicit Conversion: You can manually convert datatypes using built
in functions like Number (), String (), Boolean ().
- Common Explicit type conversion: Scenarios:
1) Number to String:
Ex: here we are converting the number datatype into string by using
String () built in function:
Let a = 1001
Let d=String(a)
[Link](d) //”1001”
[Link] (typeof d) //string
2) String to Number:
Ex: here we are manually converting the string datatype to number
Let a = “1001”
Let b=Number(a)
[Link](b) //1001
SYNTAX:
if(condition)
{
//statement
}
else if(condition)
{
// statement
}
else{
//statement
}
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);
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:
1.) Named Function: -
This is the most common way of defining named function.
- Syntax:
function funcitonName (list of arguments) {
//statements
}
functionName (list of arguments);
Example:
function sayHello(name) {
[Link] (`Hello ${name}`)
}
sayHello("JavaScript");
2) Declaration Function: -
Declaration function is hoisted, which means they can be used before
they defined in the code
- Example: function mul (a, b) {
[Link](a*b)
}
mul (10,20)
3)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);
- Example 1:
(function () {
[Link] ("this is immediate invoking functions")
}) ();
//semi colon is mandatory if not given next IIFE function won’t
execute
(function () {
[Link] ("this is iikf 2")
})();
- Example 2:
(function () {
let secretMessage="Chocolate is in the freezer"
function showSecretMessage(secretMessage)
{
[Link](secretMessage)
}
showSecretMessage(secretMessage)
})();
[Link] Function:
- It is an advanced function.
- It will reduce the code
- To execute this function, we have to store it in a variable.
- Arrow functions are concise way to write functions in JavaScript which
is introduced in ES6.
- They provide a cleaner syntax and can be especially useful for short
syntax, anonymous function.
- Syntax 1: (parameters) => {
//code to be executed
}
- Key points of arrow functions
1.) Concise syntax:
(i) For single line functions with a single expression, you can avoid the
curly braces and return keyword.
(ii) Ex: const square = (x) => x*x;
(iii) For a functions with multiple statements/ expressions or a block of
code we need to use curly braces and return keyword if we have to
return the value from that function.
2.) Implicit return: (i) As mentioned, if you omit the curly braces the
expression is implicitly returned.
(ii) Ex: let add = (a, b) => a+b [Link] (add (10,20))
3.) Parameter handling:
(i) If you have a single parameter you can omit the parenthesis.
(ii) Ex: let greet = name =>{ [Link](`goodafternoon ${name}`) }
greet ();
(iii) If you don’t have any parameter then you can use underscore (_) or
$. (iv) Ex: let greet = _ => [Link] (`good afternoon ${name}`)
[Link] Function:
- Example:
function add (a, b) {
return a+b;
}
function Calculate (callback, a, b) {
return callback (a, b)
}
let res=Calculate(add,10,20)
[Link](res)
- Example 2:
function areaOfSquare(a)
{
return a*a;
}
function mainFun (callback, a)
{
return callback(a)
}
let a=10;
[Link] ("The area of square is”, mainFun (areaOfSquare, a)) -
There are some inbuilt higher order functions present JavaScript
map, reduce and filter, setTimeOut, setInterval, for each.
- Example 1:
(function () {
[Link] ("this is immediate invoking functions")
}
) (); //semi colon is mandatory if not given next IIFE function
won’t execute
(function () { [Link] ("this is iikf 2") })();
- Example 2:
(function () {
let secretMessage="Chocolate is in the freezer" function
showSecretMessage(secretMessage)
{
[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
8) Nested Function:
A function which is present inside another function is called as Nested
Function.
It can access variables from the outer function.
That is something called as Closure function.
For Example →
9) What is Closure Function?
➢ A closure in JavaScript is a feature where a function
"remembers" its
lexical environment (the variables from the scope where it was
created) even after it is executed outside of that scope.
➢ Simply put, closures allow inner functions to access variables
from their outer function, even after the outer function has
finished execution.
NOTE: A closure is a function that has access to its own scope,
the scope
of the outer function, and the global scope.
⚫ When Closure Function will be Created?
A closure itself is not an object; it is a function. Specifically, a
closure
occurs when a function is created inside another function and
retains
access to the variables from the outer function's scope, even
after the
outer function has finished execution.
.
JS Strings
What are Strings in Javascript?
⚫ The string is the collection of characters.
⚫ Strings are immutable, means their content cannot be changed once created.
⚫ However, you can create a new string based on an existing one.
⚫ They are one of the most commonly used data types and can include letters,
numbers, symbols, and even emojis
2. charAt()⇒
Returns the character at a specified index (only positive index allowed)
Syntax →💡
[Link](index)
Return Type:
String
For Example →
3) concat()⇒
Concatenates one or more strings and returns a new string.
Syntax → 💡
[Link](str1, str2, ...)
Return Type:
String
For Example →
4)includes()⇒
Checks if a string contains a specified substring.
Syntax →
[Link](substring, startIndex)
Return Type:
Boolean
For Example →
.
5)indexOf()⇒
Returns the first occurrence index of a substring, or -1 if not found.
Syntax →
[Link](substring, startIndex)
Return Type: Number
For Example →
6)lastIndexOf()⇒
Returns the last occurrence index of a substring, or -1 if not found.
Syntax →
💡[Link](substring, startIndex)
Return Type:
Number
For Example →
7)slice()⇒
Extracts a section of a string and returns it as a new string.
Syntax →
💡
[Link](startIndex, endIndex)
Return Type: String
For Example →
8)split()⇒
Splits a string into an array based on a specified separator.
Syntax →
💡
[Link](separator, limit)
Return Type:
Array
For Example →
9)subString()
⇒
Extracts a part of a string between two specified indexes.
Syntax →
💡
[Link](startIndex, endIndex)
Return Type:
String
For Example →
10)toUpperCase()⇒
Converts a string to uppercase.
Syntax →
💡
[Link]()
Return Type:
String
For Example →
11)toLowerCase()⇒
Converts a string to lowercase.
Syntax →
💡
[Link]()
Return Type:
String
12)trim()⇒
Removes whitespace from both ends of a string.
Syntax →
💡
[Link]()
Return Type:
String
For Example →
13)trimStart()⇒
Removes whitespace from the beginning of a string.
Syntax →
💡
[Link]()
Return Type:
String
For Example →
14)trimEnd()⇒
Removes whitespace from the end of a string.
Syntax →
💡
[Link]()
Return Type:
String
For Example →
15)toString()⇒
Converts a string object to a primitive string.
Syntax →
💡
[Link]()
Return Type:
String
💡
let arrayRefVar = [value1, value2, value3, ..., valueN];
For Example →
1. push()⇒
Adds one or more elements to the end of an array and returns the new
length of the array.
Syntax →
2. pop()⇒
Removes the last element from an array and returns it.
Syntax →
💡
[Link]()
Return Type: The removed element, or undefined
if the array is empty.
For Example →
3. shift()⇒
Removes the first element from an array and returns it.
Syntax →
💡
[Link]()
Return Type: The removed element, or
undefined
if the array is empty.
For Example →
4. unshift()⇒
Adds one or more elements to the beginning of an array and returns the
new length of the array.
Syntax →
💡
[Link](element1, element2, ..., elementN)
Return Type: Number (new length of the array).
For Example →
5. slice()⇒
Returns a shallow copy of a portion of an array into a new array.
Syntax →
💡
[Link](startIndex, endIndex)
Return Type: New array
For Example →
6. splice()⇒
Changes the contents of an array by removing, replacing, or adding
elements.
Syntax →
💡
[Link](startIndex, deleteCount, item1, item2, ...)
Return Type: The Array of removed elements.
For Example →
7. concat()⇒
Merges two or more arrays into a new array.
Syntax →
💡
[Link](array1, array2, ..., arrayN)
Return Type: New array.
For Example →
8. reverse()⇒
Reverses the order of elements in an array.
Syntax →
💡
[Link]()
Return Type: The original array (reversed).
For Example →
9. join()⇒
Joins all elements of an array into a string, separated by a specified
separator.
Syntax →
💡
[Link](separator)
Return Type: String
For Example →
10. indexOf()⇒
Returns the first index of a specified element in the array, or
-1
if not
found.
Syntax →
💡
[Link](searchElement, fromIndex)
Return Type: Number (index)
For Example →
11. lastIndexOf()⇒
Returns the last index of a specified element in the array, or
-1
if not
found.
Syntax →
💡
[Link](searchElement, fromIndex)
Return Type: Number (index)
For Example →
12. includes()⇒
Determines whether an array includes a certain element.
Syntax →
💡
[Link](searchElement, fromIndex)
Return Type: Boolean (
true
if it is present otherwise false )
For Example →
3. map()
The map() method creates a new array by applying a given function to
every element in the array.
It does not modify the original array.
It iterates through each element of the array and invokes a callback
function for each element.
The result of the callback function is then added to the new array.
Syntax →
💡
[Link]((cValue, cIndex, cArray) => {
// return new value for the current element
});
Parameters:
1.
currentValue
: The current element being processed.
2.
currentIndex
(optional): The index of the current element.
3.
currentArray
(optional): The original array.
Return Type: Returns a new array with transformed elements.
For Example →
Key Points:
The original array remains unchanged.
Used for transformation purposes
4. filter()
The filter()method creates a new array containing all the elements that
pass a certain condition (provided in a callback function).
It iterates through each element of the array and invokes the callback
function for each element.
If the callback function returns true for an element, that element is
included in the new array; otherwise, it is excluded.
It filters out unwanted values
Syntax →
💡
[Link]((cValue, cIndex, cArray) => {
// return true to keep the element, false otherwise
});
Parameters:
1.
currentValue
: The current element being processed.
2.
currentIndex
(optional): The index of the current element.
3.
currentArray
(optional): The original array.
Return Type: Returns a new array containing elements that satisfy the
condition.
For Example →
Key Points:
The callback function must return a boolean ( true or false ).
Useful for removing unwanted elements.
5. reduce()
The reduce() method executes a reducer function on each element of the
array, resulting in a single output value.
The callback function takes four arguments: accumulator, currentValue,
currentIndex, and the array itself.
It is ideal used for aggregating array elements into a sum, product, or other
computation.
Syntax →
💡
[Link]((accumulator, cValue, cIndex, cArray) => {
// logic to aggregate values
return updatedAccumulator;
},
initialValue);
Parameters:
1.
accumulator
: The accumulated result from the previous iterations.
2.
currentValue
: The current element being processed.
3.
currentIndex
(optional): The index of the current element.
4.
currentArray
(optional): The original array.
5.
initialValue
(optional): The initial value of the accumulator (default is
the first element of the array).
Return Type: Returns the final accumulated (Single) valu
6. forEach()
The forEach()method executes a provided function once for each array
element. Unlike map() , it does not return a new array. It is primarily used for side
effects (e.g., logging or updating external data).
Syntax →
💡
[Link]((cValue, cIndex, cArray) => {
// perform an operation for each element
});
Parameters:
1.
currentValue
: The current element being processed.
2.
currentIndex
(optional): The index of the current element.
3.
currentArray
(optional): The original array.
Return Type: Undefined. It does not return anything.
For Example →
Key Points:
Does not return a new array.
Best for executing a function on each element without modifying the array
JS Objects
1. What is Object in Javascript?
In Javascript object is a collection of multiple different properties in the form of key-value
pairs.
An object is a programmatical representation of real life entity.
Property → It is the combination of key and value pair
3. Functional Constructor ⇒
A functional constructor is a function that is used to create and initialize objects when
called with the new keyword.
You can define a custom constructor function to create multiple objects with the same
structure.
[Link]() ⇒
Create a new object by copying properties from one or more existing objects
Method in Javascript
1. What is a Method in JavaScript?
In JavaScript, a method is simply a function that is stored as a property of an object.
A method is essentially a function that belongs to an object.
. Different Ways to Define Methods
Important Note: Arrow Functions and this
In the example above, [Link]'t work as expected because thisinside an arrow function does not refer
to the object ( obj ). Instead, it refers to the surrounding scope
4. Correct Way to Use this in Object Methods
To make sure the method works correctly and accesses the object properties using
this you should avoid using arrow functions as methods.
Always use regular function syntax (or ES6 shorthand) to define methods inside objects
💡
[Link]( target_object, sources );
Return Type → It will return the target object.
For Example →
2. [Link]() ⇒
The [Link]() method prevents additions or deletions of new properties.
But we can modify the property.
Syntax →
💡
[Link]( obj );
Return Type → It will returns the object which has been sealed.
For Example →
3. [Link]() ⇒
The [Link]() method can be used to check if an object is sealed.
The [Link]() returns trueif an object is sealed.
Syntax →
[Link]( obj )
4. [Link]() ⇒
The
[Link]()
method prevents any changes to an object.
Frozen objects are read-only.
The
[Link]()
method freezes an object that we can not add new property, modify the
property and delete the property.
Syntax →
💡
[Link]( obj );
Return Type → It will return the frozen object.
For Example →
5. [Link]() ⇒
The
[Link]()
checks the passed object is frozen or not.
Syntax →
💡
[Link]( obj );
Return Type → It will return the boolean value
true
if the object is frozen and
false
if not.
For Example →
6. [Link]() ⇒
The [Link]() method returns an array with the keys of an object.
The [Link]() method does not change the original object.
Syntax →
💡
[Link]( obj );
Return Type → It will return an array containing the keys of the object.
For Example →
;
8. [Link]() ⇒
The [Link]() method returns the each key and value pair in the form of array.
(nested array) Get an array of [key, value] pairs.
The [Link]() method does not change the original object.
Syntax →
💡
[Link]( obj );
Return Type → It will return an iterable array of the object in the form of key-value pairs.
For Example →
9. [Link]() ⇒
The [Link]() method creates an object from a list of key-value pairs.
Syntax →
💡
[Link]( arr );
Return Type → It will return object created from the key-value pairs.
2. Spread Operator
The spread operator is used to spread or unpack the elements of an
array (or object) into individual elements.
This is typically used when calling a function, or when creating a copy
of an array or object.
It is used inside a function call, or when copying arrays/objects.
Spread Operator spreads the values in a new container and creates a
shallow copy
Example-1: Arrays
Example-2: Objects
Example-3: Strings
It will spread each and every character from the given string.
1. Array Destructuring ⇒
Rest Parameter in Destructuring:
2. Object Destructuring ⇒
Synchronous vs
Asynchronous
Javascript
1. What is Synchronous Javascript?
In synchronous JavaScript, code is executed line by line in the order it
appears.
If a task takes time (e.g., reading a file or fetching data from a server), it
blocks the execution of the following lines until the task is completed.
. setTimeout()
The setTimeout() executes the function once after a specified delay (in
milliseconds).
The setTimeout() is executed only once.
Syntax →
💡
let timerId = setTimeout(callback, timeInMilliseconds);
clearInterval()
The clearInterval() stops a repeating task set by
setInterval()
Syntax →
clearInterval(intervalId);
setInterval()
The setInterval() executes the function repeatedly at specified time
intervals (in milliseconds).
Syntax →
💡
let intervalId = setInterval(callback, timeInMilliseconds);
Use case: Perform tasks repeatedly (e.g., updating a countdown or clock).
For Example →
. clearTimeout()
The clearTimeout() stops a timeout set by setTimeout()
.
Syntax →
💡
clearTimeout(timerId);
Use case: Cancel a delayed task if it's no longer needed.
For Example →
JS Promises
What is a Promise?
A Promise in JavaScript is an object that represents the eventual
completion or failure of an asynchronous operation and its resulting value.
The Promise Object represents the completion or failure of an
asynchronous operation and its results.
States of a Promise:
1. Pending: The promise is in its initial state, neither fulfilled nor rejected.
2. Fulfilled: The promise is successfully completed, and the resulting value is
available.
3. Rejected: The promise failed, and an error or reason is available.
Creating a Promise
ou can create a promise using the Promise constructor.
The syntax is:
💡
let myPromise = new Promise((resolve, reject) => {
// Perform some asynchronous task
// Call resolve() if successful
// Call reject() if there's an error
});
resolve
is a function used to mark the promise as fulfilled.
reject
is a function used to mark the promise as rejected.
Promise Chaining
Promise chaining allows you to perform a sequence of asynchronous
tasks where the next operation starts only after the previous one finishes
JS Fetch API
What is the fetch API?
The fetchAPI is a modern way provided by browsers to fetch resources
from servers (like APIs, files, etc.).
It allows you to make network requests and retrieve data (e.g., JSON data from an
API or a webpage).
The fetch API is built on promises, making it easier to handle
asynchronous operations.
Key Terms:
Collection: A collection of documents.
Document: A collection of fields (fields are key-value pairs).
Syntax:💡
[Link](string)
2.
[Link]()
⇒
converts JavaScript objects into JSON strings,
[Link]()
accepting a single object argument.
When sending data to a web server, the data has to be a string format.
Convert a javascript object into a string with
[Link]()
.
Syntax →
[Link](object)
BOM Objects
The key objects in the Browser Object Model are:
1. Window: The main global object representing the browser window/tab.
2. Document: Represents the HTML document loaded in the window.
3. Screen: Provides information about the user's screen (like width,
height, etc.).
4. Navigator: Contains information about the browser (user agent,
platform, language, etc.).
5. Location: Represents the current URL and allows navigation to other
pages.
1. Document ( [Link] )
The document property refers to the HTML document loaded in the
browser window.
The JavaScript document object is a property of the window object
It can be accessed using [Link]
syntax. It can also be accessed without prefixing window object