[go: up one dir, main page]

0% found this document useful (0 votes)
16 views1 page

Javascript

The document provides an overview of JavaScript, covering output methods, script tag placement, variable declaration, data types, operators, functions, and objects. It explains various ways to write and utilize JavaScript code, including comments, hoisting, strict mode, and template literals. Additionally, it discusses the lifecycle of variables, the importance of functions, and the creation of objects in JavaScript.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views1 page

Javascript

The document provides an overview of JavaScript, covering output methods, script tag placement, variable declaration, data types, operators, functions, and objects. It explains various ways to write and utilize JavaScript code, including comments, hoisting, strict mode, and template literals. Additionally, it discusses the lifecycle of variables, the importance of functions, and the creation of objects in JavaScript.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Javascript

Output possibilities

1. console.log: It is used to display the output in the console of the browser.

2. alert: This is used to display the output in a separate pop up box on the browser.
It does not require us to open the console like in previous method.

- The disadvantage for alert is that it halts the execution of the program
until the confirmation of alert.

3. document.write: This is used to display the output of the JS code on the webpage
itself. The output can even be displayed in the form of HTML elements.

4. innerHTML: This method displayes our output in a particular HTML element.


It also supports the HTML tags in the output.,

Effects of <script> tag placement:

1. In the head section: The JS code in the script tag will start its execution before HTML
elements are loaded.
-Due to this, if we want to work with any HTML element, we
won't be able to do it and will get error.
- It there is any code in this script tag which is lengthy and
might take time, it will affect the performance of our page.
The page will be displayed properly only after that code is finished

2. At the end of body section: When the script tag is written in the end of body section,
it will get the necessary HTML elements for its operation.
If there is any lengthy code in this script tag, it won't
hamper the performance of the HTML page.

Ways to write JS:

1. External JS: It is the typew of JS which is written in a separate file having '.js'
extension and connected to the HTML document using <script> tag.

2. Internal JS: When we write the JS code in the same HTML document usnig <script> tag,
it is called Internal JS.

3. Inline JS: When the JS code is written in the body of the opening tag of any
elmement, it is called inline JS

Where to write JS:

1. In VS Code:
JS Code is written in the VS code in a new file when we want to use the
code as functionality and make it permanent

2. In the console of the browser:


We write the code in browser console when we want to
use temporarily for that particular webpage.

Comments:

1. Single line comment (//)

// This is a single line comment


// Lets us try adding comment to this line

2. Mulitline comment (/* */)

In this, we can create comments which are mafe up of multiple lines.


It allows us to hit enter in between so that our comment is better
readable and understandable

It is additonal line
*/

Variables :

Variables are the containers which are used to store some data which can be later
used for processing.
The variables are made up of two parts:

1. Declarator

2. Identifier

Declarators

These are the keyowrds which specify the scope of any variable
Scope is the area where the variable should be applicable.
If the scope is improperly defined then the variable may get access to
other parts of code where it can cause issues.

There are three declarators in JS:


1. var
2. let
3. const

var:
This is a declarator from older JS
This is a global scope declarator
It can be redeclared and re-assigned

let:
It is a feature from ModernJS(ES6)
It is a block scope declarator
It cannot be redeclared but it can be re-assigned

const:
It a feature from ModernJS(ES6)
It is also used for creating a block scope declarator
It cannot be redeclared nor re-assigned

Lifecycle phases of a variable

1. Declare:
In this phase we only create a container/variable having declarator and identifier.
We do not store any data in this yet.

2. Initialize:
In this phase, we actually store some data into the container/variable

3. Use:
In this phase, we use the variable with data stored in it for some processing.

Identifier

The identifier is the name given to a variable which can be used for uniquely
identifying the given variable

Rules to write identifiers:

1. The name of the variable should not be any reserved keywords (if, while, for, let, var,
const, do, new, in)
2. The name of the variable should not contain any spaces
3. Instead of spaces we can use PascalCasing or camelCasing
4. We cannot use any other symbol than '$' or '_' in our variable name
5. The variable name cannot be a number or it cannot start with a number

Hoisting :
• It is the default behaviour of Javascript
• It allows us to declare our variable later on after intializing and using it first.
• When we declare our variable after intialization and use, Javascript internally takes
• the variable to the top of the code.

• Because of this, the variable comes in the original flow of the variable lifecycle and
• thus gets executed properly

• At times, the developer can also forget declaring the variable due to the
• hoisting behaviour of Javascript.
• This can create problems in the execution and troubleshooting of the JS code.

• The concept of declaration is only applicable on var.

• let and const do not support hoisting.

use strict :

• It is a rule/pragma which tells our browser how to execute the javascript code.
• It puts our browser on 'strict mode'
• Because of this, the use of undeclared variables is prevented.

• This helps the developer to write cleaner codes which will be better for execution
and for troubleshooting

• 'use strict' can be used in blockn scope as well as on the global scope.

Data types in JS:

1. Primitive data type

2. Non-Primitive data type

1. Primitive data type:


number:
It is used to store numerical values upon which we we perform some
arithmetic operations.

string:
It is a collection of characters which is stored between two double
quotes.
boolean:
It is used to give 'true' or 'false' values

undefined:
It is given when we create a variable but do not store any value in it.
Since JS is a dyanmically written langauge, it detects the datatype of the
variable at the time of execution.
If there is no value stored in the variable, JS cannot determine the datatype of
the variable.
Thats why it gives us undefined

null:
When we do not get any object in the variable it returns null.
null itself has datatype 'object'.
It denoted empty colletion/object.

bigInt:
It is used to store very large numbers in the integer format(without decimal
point) To make a number bigInt, we need to insert 'n' at the end of the number.

Symbol:
It is a datatype from ModernJS(ES6)
It is used to generate unique values.
Never two keys will be be the same.
The Symbol can be used as the unique key for any object.

Basic Operators

Arithmetic operators:

+,-,*,/,%

Assignment operators

=, +=, -=, *=, /=, %=

Comparison operators

<, >, <=, >=

Logical operators

!, &&, ||

Incr/Decr operators

++, --

Equality operators

== (Value equality), === (Strict equality)

ModernJS operators :

1. typeof:
This operator helps us to find the datatype of the variable

2. nullish coelscheing:
It provides some default value for the variable to work properly.
Otherwise the variable shows 'undefined' output.
Syntax:

var_name??"Default_value"

3. ternary operator:
This reduces the efforts for writing the if-else block

Syntax:
condition ? [If the condition is true] : [If the condition is false]

4. exponential operator:
This operator is used to raise a number to the power of other number

Syntax:

number ** power

5. concatenation operator:
It is given by '+' sign and it is used to join together string
or strings with variables.

TEMPLATE LITERAL

-Ways to display the strings and variables together in JS

1. Use of multiple document.write():

Because of this appraoch, we need to write multiple lines of code just to get a
simple output with multiple variables in it.

2. Use of concatenation operator (+):

• This method helps us to write our output in a single line but in this we need
to use multiple inverted quotes ad concatenation operators.
• Even if we miss one of the quotes or operators, our entire output can go wrong.

3. Template Literal:

• It is a feature of ModernJS(ES6) to write outputs.


• If we work with concatenation operators, we can find problems while using single
quotes or double quotes
• Also we need to pay proper attention to the use of concatenation operators for
writing variables
• By using Template Literal, all of the above problems are solved using the ``(backtick)
symbol.
• The output that we want to dispay is written in these backtick symbols and the
variables are
written in the '${var_name}'
• Also, we can easilt write the quotes symbols inside these backticks.
• Template Literal makes our job of writing symbols and variables much easier.

Typecasting

It is the process of converting the datatype from one form into another.
It is required so that we can use the data appropriately.

1. Modifying the prompt:


We add the '+' as prefix to the prompt method. It converts the data in prompt
to a number. Prompt gives a string by default.

2. Number():
• This method helps us to convert our string into a number including the decimal values.
• Because of this method, we can convert the decimal strings into decimal numbers.

3. parseInt():
• This method helps us to convert our string into a number while ignoring the decimal
values.
• This method stops the conversion of the string as soon as it finds any non-numeric
character.

IQ: Explain the difference between Number() and parseInt()

Conditional statement

##

Iterative Loops

In this, we exeute our code miltiple times until the given condition is valid.
Once the condition is invalid the execution of code stops.

For working with the iterative loops we need:

1. A variable(Conditional variable)
2. Initializtion of the conditional variable
3. OPeration of conditional variable

• do-while

syntax

do{
Code block
}while(Condition)

• Disadvantage:
1. The syntax can get problematic at the times of debugging
2. The code gets executed at least once even if the condition is invalid

• while

syntax

while(Condition){

Code block

Advantage:
1. The syntax is more developer friendly while debugging
2. The code does not get executed at all if the condition is found invalid.

• for

syntax

for(let i=0; i<=10; i++){


Code block
}

Advantage:
1. It helps the developer by keeping the conditional variable declaration,
condition, and operation together.

Function

It is a non-primitive datatype in JS
It is used to create reusable code blocks which can be used whnever and wherever
necessary
It prevents the code from getting lengthy and errors from re-writing the same code lines.
The function works in two stages:
1. Declaration: We write the code block to be executed in this phase.
2. Calling: We exeute the given block using the name of the function

Syntax:

Declaration

function function_name(){
Code block
}

Calling
function_name()

Component of a function

1. Parameter: It the idea that we give to the function in form of variables


which will be used for performing desired operation.

2. Arguments: This is the actual data that we pass in function call and which
is used in paramters to perform the given operation

Extra arguments:

In Javascript, the arguments that we pass to a function are stored in a collection.


From this collection only those number of arguments are used as the number of
parameters.
But that does not mean that we have to pass only that much arguments as the parameters.
Javascript allows us to pass more arguments than the parameters without giving any error.
These extra arguments can be used/handled by the concept of rest params.

In rest params, all the extra arguements are stored in a collection which can later be
used for any desired purpose.
For this, we use rest operator.

Rest operator is a modernJS operator(ES6)


It collects all the individual elements and stores them within a collection.
We can then use this collection for our required purpose.

Ways to write functions is JS

1. Named function/Normal function:


This is the most common way to write a function.
We write a function using 'function' keyword and we call it using the name assigned
to the function.
The named functions are hoisted, i.e. they can be called even before declaring them.

2. Variable named function/Variable expressions:


In this type, we crate a normal function and store it in a variable
For calling this function, we need to call the variable. If we call the stored function, it
gives error
The variable named functions are not hoisted.

3. Anonymous functions:
It is somewhat similar to a variable named function, only the difference is that the
function
stored in the variable does not have any name.
For calling this function, we need to call the variable in which the function is stored.
This type is commonly used in callback functions.

4. Self invoking functions:


This is a type of function which calls itself automatically after it is declared.
It is written like an anonymous function but it is written in '( )' without storing in any
variable
This type of functions are used to perform some action as soon as the page is
loaded.
5. Arrow functions(Fat arrow/Lambda):
It is a function from ModernJS(ES6)
It replaces various types of functions especially anonymous functions.
This type is very commonly used in callback functions.
It does not involve writing the function keyword, instead, it directly uses the '()', '=>'
and '{}'
Rules for writing the '{}' in arrow function:
1. It does not need '{}' if the code block is of one line.
2. If the code is of multiple lines or if the single code has return keyword, then the '{}'
are mandatory

Return keyword :

When we calculate any value inside a function, it stays valid only until the function is being
called
The moment function call ends, the values inside function lose their existance.
If we want to use any value from inside the function on the outside, we won't be able to
do that.
For this, return keyword is useful.
Using return keyword, we can send a value from within the function to the outside of
function.
This value can be stored in a variable or displayed directly.
Using this return keyword, we can use our function to calculate values and use them
anywhere as per
the requirement

The function execution stops where return keyword is used.


For this, always make sure to use return keyword at the end of the function.

Callback function:

It is a function which is passed as an argument to another function.


This callback function is executed inside the main function and its output is then used in
the main function.

It is a type of asynchronous behaviour

Nested functions:

These are the functions which are declared within a main function and are used only
within that function.
Such functions are mostly made up of logic which is limited to that particular main function
itself

Object

It is one of the most fundamental concepts in JS


Objects are the enitites which are used to store very large amounts of data.
They have no limitation on the data storage, i.e. we can store any amount and any kind of
data in them.
The data stored within an object is individaully identified by referring to its 'key'
This is called key-indexing.

Ways to create object:

1. Literal method:
• We simply create a variable and store an object in the variable.
• This method is useful to create standalone objects.

2. Instance method:
• This method is used to create an object using "new" keyword and then
store the data in the object.
• This method can be used on other datatypes as well to create their objects.
This method is useful while creating multiple objects.

3. Constructor method:
• In this we use a constructor to create multiple objects of similar type.
• Constructor is a speacial type of function which is used to intialize
values to an object.
• This constructor is useful when we want to create multiple instances of same object
type.

Methods

These are the functions which are stored within an object and use the
data in the obejct to generate some output

Proper definition of object:

The objects are entities made up of properties and methods which are used
to store very large amounts of data in form of key value pairs

properties: The data stored in the object is called property


E.g. name:"Rutvij"

Object Processing :

Key referencing :
This is used when we directly want to access the key from any object.
In this, the key is referred using the '.'

// myObj1.location = "Pune";
// console.log(myObj1);

// let userKey = prompt("Enter the data you want to change"); //location


// let newData = prompt("Enter the updated value"); //Pune

Variable referencing :
This is used when we have the name of key stored in a variable and we need to
use that variable to access the obejct key
For this, we write the variable in '[var_name]' to find the key within the object.

*/
// myObj1[userKey] = newData;
// console.log(myObj1);

Object methods :
• Object.keys():
• It returns a collection of all the keys from the object

• Object.values():
• It returns all the values frmo the objects in form of a collection
• Object.entries():
• It returns a coleection of arrays made of the key value pairs in the given
object.

• Object.getOwnPropertyNames():
• It returns a colelction of all the enumerable and non-enumerable properties in
the object.

• Object.is():
• It checks whether both the arguments passed are exactly or not

• isFinite():
• This method check whether given value is Finite or not

• inNaN():
• It checks whether the given value is Not a number.

• Object.freeze():
• This method prevents modification of the values and also
• it does not allow adding any new keys to the object

• Object.isFrozen():
• It checks whether the object is frozen or not.

• seal():
• This method prevents adding any new keys to the object but we can
• modify the values of existing keys

• Object.isSealed():
• It checks whether the object is sealed or not.

Array

It is a collection of similar/dissimilar elements


Since JS is a dunamically written language, we do not need to specify the datatype for the
array
Due to this we get the freedom of storing any kind of data in the array.
The elements stored in the array are identified based on their position in the array
This is called numerical indexing
The forst index position starts from 0 and the last index position is no.of elements-1

The datatype of an array is 'object'. To check whether the variable contains an array, we
use Array.isArray()

• Ways to create an array:

1. Literal method

2. Instance method

Basic methods is array :

• length:
• It returns the no of elements in the array

• push:
It adds a new element at the end of the array
It returns the modified length of the array

• pop:
It removes one element from the end of the array
It returns the removed element from the end of the array

• unshift:
It adds an element to the beginning of the array
It returns the new length of the array after adding a new element in the
beginning

• shift:
It removes one element from the beginning of the array.
It returns the element which was removed from the beginning of the array

• splice:

splice(starting_index, no_of_elements): It removes the given no of element from


the starting index

• splice(starting_index, no_of_elements, replacement_elements):


It removes the given no of elements from the starting index
and keeps the replacement elements in that place

• splice(starting_index, 0, replacement_elements):
It does not remove any elements from the array but it
keeps the replacement elements in the given starting index

Array additional methods :

• indexOf():
This method returns the index position of the first occurenace of the element.

• lastIndexOf():
This method returns the index position of the last occurence of the element.

• Array.isArray():
This method check whether the object passed is actually an object or an array.

• includes():
This method checkn sfor the presence of the given element within the array.

• fill():
THis method replaces the array elements with the static data(The data is constant).
It modifies the original array

• slice(starting_index, ending_index):
This method extracts a portion of our array and returns it.
It does not modify the original array
It supports negative values

• reverse():
This method reverses the array and it modifies the original array.

• sort():
This method arranges our array elements in alphabetical or numerical order.

• toString():
This method converts the array into a string.
It is a universal method, i.e. it is applicable for all datatypes.

• join(seperatorCharacter):
This method joins all the elements of array together
using the provided seperator character. It coverts the output to a string.

• concat():
It joins together arrays.

• flat():
It merges the nested array within an array in to the main array.

• valueOf():
It is used to return the as it is value of the given array.

• from():
It converts a string into an array

• filter(callback):
This method uses a callback function to check the elements and return only
those elements which match the given condition.

This method filters the array elements as per the given codition.

• some(callback):
This method uses a callback function to check every element with a condition. If
any of elements matches the condition it returns true.
This method returns false only when none of the elements matches the
condition.
• every(callback):
This method uses a callback to check whether all the elements match the
condition.
It will return true only when all the elements are matching the condition.
If a single element does not match the condition, the answer will be false.

• reduce(callback):
This method uses a callback function to process eacch and every element from the
array and return a single value

IQ: What is the difference between slice and splice?


• Slice
1. It extracts a portion of array
2. It takes starting index and ending index as arguments
3. It does not modify the original array

• Splice
• 1. It replaces, removes or adds the elements into the array
2. It takes starting index, no of elements and replacement elements as arguments
3. It modifies the original array

String :

The string is a primitive datatype.


The string is a collection of characters written between " "
These characters could be alphabets, numbers, symbols or combinations of all of them.
String also follows numnerical indexing just like an array.
The first character has the index position as 0 and the last index position is no. of
characters-1

Ways to create a string:


1. Literal method
2. Instance method

String in-built methods :

• length:
It returns the count of characters in the string.

• slice(strating_index, ending_index):
It extracts a portion of string from the starting index
till before ending index. It supports the negative indices.

• substring(straing_index, ending_index):
It extracts a portion of string stating from the
given starting index till before the ending index. It does not support negative
indices.
The output with negative index positions is illogical.

• substr(starting index, no of characters):


This method also returns the extracted portion from a string,
but it takes the starting index and the no of characters as the arguments.

• touppercase() and toLowercase():


Converts our string into capital letters or small letters

• concat():
This method concatenates strings together.

• indexOf():
It returns the index position of first occurence of the given character

• lastIndexof():
It returns the index position of last occurence of the given character.

**The above two methods will return -1 in case the element is found in the given string. This is
because
the string has positive index positions starting from 0. If the return is negative, that means no
such index
position is present and it symbolizes that the element is not present in string

• split('separator character'):
This method divides our string into array elements from
the given separator character.

• trim()/trimStart()/trimEnd():
These methods helps us to remove the whitespace from
the starting or ending of the string

• includes():
It check whether the given character/string is present in the string or not.
It is case sensitive.

• replace():
This method replaces the first occurence of the given character/string with
the replacement string/character.

• pad()/padStart()/padEnd():
These methods increase the length of the string to the desired
length by adding some character to start or end of the string.

IQ: What is the difference between slice() and substring()?


IQ: What is the difference between slice(), substring() and substr()

Events :

The actions that are performed on a website using the inputs devices(mouse, keyboard),
window or forms
are called events

Javascript is an event driven language, i.e. it can respond to these actions by performing
some or
other task

'on' is a prefix used while writing the event.

In JS, we get four types of events:

1. Mouse events
2. Keyboard events
3. Window events
4. Form events

Mouse events :

The actions performed using the mouse are called mouse events.

1. onclick: This event occurs when we click the left mouse button
2. ondblclick: This event occurs when we double click the left mouse button
3. oncontextmenu: This event occurs when the mouse right button is clicked
4. onmouseover: This event occurs when the mouse pointer enters the element area
5. onmouseout: This event occurs when the mouse pointer leaves the element area.
6. onmousewheel: This event occurs when the mouse scroll wheel has been rotated
7. onmousedown: This event occurs when any mouse button is pressed down
8. onmouseup: THis event occurs when any mouse button that has been pressed in is left.

Keybaord events :

1. onkeypress: This event occurs when we press any printable key on the keyboard
(alphabets, symbols, space, enter, etc). This is deprecated event,
instead of this we use keydown event

2. onkeydown: This event occurs when any key of the keyboard is pressed.
This event is now used to identify the key combination in various platforms

3. onkeyup: This event occurs when any keyboard key that has been pressed in is
un-pressed

Window Events :

1. onload: This event occurs when the page is loaded successfully

2. onscroll: This event occurs only when the scrollable content gets scrolled.
This event will not occur if there is no scrollable content and still
the mouse wheel is rotated.

3. onresize: This event occurs when the size of the element is changed.

IQ. Difference between onmousewheel and onscroll?

Form Events :

Form is used to collet the data from user using input tags and submit the
data to the backend for further processing

1. onfocus: Focussing means clicking on the input field. The onfocus event occurs
when we focus onto any input field.

2. onblur: This event occurs when we click out from anyu input field and de-select it.

3. onchange: This event occurs when the data in the input field has been changed.

4. onselect: This event occurs when the data in the input field gets selected.

5. onsubmit: This event occurs when the form is getting submitted.

IQ: What is the difference between <input type="submit"/> and onsubmit?

DOM

DOM stands for Document Object Model


Our browser interprets the HTML code in form of a tree data structure.
In JS, we cannot work with this tree data structure.
For that, the HTML code is represented in form of a JS object and it is called a DOM.

Using this DOM, we can access and modify the HTML elements through JS code.

The DOM is represented by 'document' keyword in JS.

Methods to access HTML elements:

1. getElementById:
Returns the particular element having the given id

2. getElementsByClassName:
It returns a collection of all elements having the given class

3. getElementsByTagName:
It returns a collection of all elements of the given tag name

4. getElementsByName:
It returns a collection of all elements having the given name

----------------------------------

1. querySelector(#id, .class, TagName, Name):


This method gives us the flexibility to
access any element of any selector type but it returns only the first
element of that given selector

2. querySelectorAll(#id, .class, TagName, Name):


This method also gives us the flexibility
to use one method to select any element of any selector type, but it returns
a collection of all the element found under that selector.

DOM methods for working with the content

1. innerHTML

Returns: It returns all the HTML content inside the given element.

Setting: It changes the HTML content inside the given element. It supports the
HTML tags.

2. outerHTML

Returns: It returns the HTML content from the element alonf with the element itself.

Setting: It replaces the entire element with the new given HTML content. It also
supports the HTML tags

3. innerText:

Returns: It ignores the HTML elements and returns only the text content from the
given element.

Settings: It changes the text content of the element and prints the HTML tags as it
is. It does not support the HTML tags

4. outerText:

Returns: It returns the text content of the element.

Setting: It replaces the entire element with the given plain text content.
It does not apply the HTML tags.

5. textContent:
It returns the text content of the element with all the HTML indentations.

BOM

BOM stands for Browser Object Model


It returns the browser in form of a javascript object
Using this BOM we can work with our browser from the JS code.

The BOM is represented using the keyword 'window'


This is a global level object.
It is present in our code everytime even if we particularly don't write it.
Apart from 'window', 'this' is another global level object.

Dialog boxes in BOM:

1. alert

2. prompt

3. confirm

Objects in BOM:

1. history: It helps us to work with the history of the browser


back(): Goes one page behind in history
forward(): Goes one page ahead in the history
go(no_of_pages): Goes given no of pages forward or behind in the history

2. location: It gives us information about different parts of URL

3. navigator: This gives us information about the browser and the user environment
(our device)

4. screen: This returns all the information about the screen of the device.

BOM methods:

print(): It can print our webpage through JS code


open(link, target, features): It helps us to open a new page using JS code for buttons
close(): This method helps us to close the pages which were opened using the open()
method

Math Object :

JS gives us the math object which has many constant from mathematics and some
methods to perform mathematical operations.
pre-built

1. min():
This method returns the smallest number from given arguements.
It does not directly work with collection.
To implement this and max() on a collection we need to use spread operator.

2. max():
This method returns the largest number from the given arguments.

3. floor():
This method rounds off our decimal value to the previous integer.

4. ceil():
This method rounds off our decimal number to the next integer.

5. round():
This method rounds off our decimal avlue to an integer value based on the decimal
place
DP > 0.5 -> Next integer
DP < 0.5 -> Previous integer
DP == 0.5 -> Next integer

6. trunc():
This method removes the decimal value from the number and returns a pure integer

7. random():
This method returns a random number between 0 and 1

8. sqrt():
This method returns the square root of any given number

9. cbrt():
This method returns the cube root of any given number

10. pow():

Spread operator :

1. Spread operator is a feature from Modern JS


2. It works exactly opposite of Rest Operator.
3. It is denoted by '...'
4. The work of spread operator is to take out individual elements from a collection
and supply them to the method

Asynchronous Behaviour of JS:

JS is a single threaded language and thets why is works in Synchronous manner.


It means that the code will get executed lnie by line from top to the bottom.
In this case the functions which take time to execute makes others functions wait for their
turn.
To avoid this asynchronous behaviour is implemented.
In asynchronous behaviour JS can hold or block any function can can take time and allow
other
functions to perform their execution.

Because of this the time taking functions can perform in their own time while the
other function carry out their work
This asynchrnous behaviour can be implemented using:

1. callbacks
2. async and await
3. promises
4. setInterval
5. setTimeout

setInterval(callback, time_interval):
This method takes two arguments, i.e. a callback function and time interval in milliseconds
It executes the given callback function repeatedly after the given interval.
If their is any function performing its task, it will continue its work without being
interrupted by this ssetInterval.
This is how the setINterval will perform its task asynchronously.

To stop the execution of setInterval, we get a method called clearInterval()

setTimeout(callback, time_interval):

This method also takes two arguments, i.e. a callback function and time interval in
milliseconds
It will start the execution of the callback function after the given time interval.
But it executes the callback function only once.
after execution the setTimeout will stop

You might also like