Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
721 views

JavaScript notes final

js notes

Uploaded by

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

JavaScript notes final

js notes

Uploaded by

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

JavaScript

It is used to provide the functionality to the webpage.

Specification OF JS:
1. JavaScript is object-based scripting language. In JavaScript we don’t want to create a class in order to object
directly we can create the object using “curly braces {}” and we can define the properties and method
Example:
let o = {
a:10;
getData : function(){
}
JS don’t have any compiler it is having only the interpreter
2. JS is a Dynamic Language: We can Dynamically change the data in JS ,i.e. if we defined the data in number
datatype we can reinitialize with other datatype also
Example: let a=200;
a=true;
3. JS is an interpreter language: it doesn’t have any compiler it is having only the interpreter which is responsible
for the code execution inside JavaScript engine. And interpreter execute the code line by line and left to right
4. JS is synchronous in nature: the same line of the code will wait until the execution of the previous line this is
called synchronous behavior
5. JS is loosely typed scripting language: it will not follow the strict syntax, but JS is case sensitive

How to Execute the JS code


We can execute JavaScript code in two ways

1. Browser (Client Side): if we want to execute in browser side, we have to create HTML file and using <script> tag we can
define the JavaScript code which should be present inside the head or body tag.
Otherwise, we can create external file with .js extension and we can link with HTML file suing <script> tag and src attribute
2. Server Side: in order to execute in server side, we should install node and node is the runtime environment which is used to
execute the JavaScript code in the Server Side
To execute the code, we should pass the command “node filename.js”

Variable In JS
1. Variables are the containers which holds the data which can be any datatype
2. We can declare the variable in JavaScript using var, let, const keywords
Var let const
Syntax var a=10 let a =10 const c =20
Scope Global script script
Declaration T F F
Reinitialization T T F
const variable must be initialized at the time of declaration otherwise it gives Syntax error
we can declare any var variable the same identifier cannot be passed to other let and const variables
Tokens:
1. are smallest unit in every programming or scripting language
2. it is building blocks of every programming language
3. in tokens we have identifier, keywords, literals and operators
Identifier
1. identifiers are the names which is given to function, variable, class
identifier rules
 it should not start with number
 except $ and _ no other special characters are allowed
 identifier should not be the keywords
keywords
1. keywords are the predefined or reserved words
2. each and every keyword have some functionality
literals
1. literals are the values which is passed to the variable which can be any datatype
operators
1. it is used to perform the operation
datatypes
1. datatype defines what type of data or what kind of data store in the variable
primitive datatypes
1. number: in number data type we can store the values within the range of –(253-1) to +( 253-1) which can be
decimal or number
2. boolean: in this we can store only two values either true or false
typeof keyword
1. it is used to check the datatype of the data
string:
1. it is used to store the bunch of characters which can be numeric or alphabets or special characters
2. every characters should enclosed within double “ single’ or back ticks `
3. string is the indexed datastructure and the indexed position always start from 0

what is the advantage of using backticks ` or template literals?


 It is used to perform interpolation within the string
 The expression should be passed within ${}
bigint
1. We can store the big integer in bigint datatype and it should be suffixed with “n”
null
1. It is used to derefer the object
2. The data type of null is object
undefined
1. If we just declare the variable and not passing value or initializing the variable and try to access the variable it will
return undefined
2. The datatype for undefined is undefined
NaN
1. Is any arithmetic operation could not able to perform between to datatypes it will return NaN
2. The datatype for NaN is NaN

Typecasting
1. Process of converting one datatype to another is k/as typecasting
Implicit typecasting
1. The data is converting one datatype to another internally the it is called as implicit type casting
Explicit typecasting
1. The data is converting one datatype to another manually by using inbuilt methods such as
parseInt(),parseFloat(),toString()
2. parseInt():it is used to convert string into number datatype i.e only integer
3. parseFloat():it is used to convert string into decimal value
4. both parseInt and parseFloat methods could not able to convert string into number datatype then it will return
NaN
5. toString(): it is used to convert other datatype into string datatype

non-primitive datatype
1. function-
 it is a set of instruction which is used to perform some tasks or functionality
 syntax – function fun_name(){}
 to call function – fun_name();
 function will execute only if the function calling statement is there
parameter
 parameters are the containers to store the argument value
arguments
 arguments are the values which is passed to the parameter which can be any
datatype
note-> you can assign the default value for the parameter by directly passing the value in the
function declaration
 return Statement
Every function will return one value which can be any datatype function
Return statement should be present at the last within the function
If no values are return by the function then take the value as undefined
 return type
it is a datatype of the data return by a function

JavaScript output methods


1. console.log()
it is a printing statement
console is a object or log() is function
2. document.write()
i) it is used to display some content in the browser window
ii) document is an object and write() is a function
a)difference between document.write() document.writeln()
b) write method not give space
c) writeln gives single space
3. alert()-> is a popup method
it is used to display alert mesg to the user
return type is void
4. confirm() -> this is also a pop up method it is used to ask the user to confirm the msg
it will return Boolean value true if the user click ok and false if clicks cancel
5. prompt()
it is a popup method and it is used to take input from the user
it will return string or null

use strict
 this statement should be present at the top of the javascript code
 it will follow the strict syntax
 for example: if the variable is declared without var let and const keyword it will throws
error
 it will not allowed duplicate parameters in the function

Scopes in javascript
1. global scope: if the variable is declared with var keyword globally then it will allocate
memory in the global scope
2. script scope: if the variable is declared with let and const keyword globally then it allocates
the memory in the script scope
3. local scope: if the variable is declared with var, let, const inside the function then it will
allocate the memory in the local scope
Parameters also belongs to the local scope
4. if the variable is declared with let and cost inside the block then it will allocate the memory
in the block scope
If the variable is declared var keyword inside block then it will allocate memory in global scope

Note: local scope variable we could not able to access in the global scope but global scope
variable we can access in the local scope
Local scope will gets created only if the function calling statement is there

Javascript debugger
 It is used to check line by line execution and memory allocation
 To start the debugger, go to console window ->sources-> click javascript file->click on line
number from where you want to check the line by line execution and click on reload or
refresh button
 To stop the debugger, click on the same line and click on reload or refresh button

Types of function:
1. anonymous function: function with no function name
Syntax: function(){}
2. named function: function with function name is k/as named function
Function name is also an identifier
3. function with expression: assigning function as a value to the variable is k/as function with
expression
4. arrow function: arrow function was introduced from the version ES6
It will reduce the syntax.
In arrow function no need to pass the function keyword only
Syntax: var arr = () => {}
“=>” this is called fat arrow
5. immediate invoked function expression (IIFE): this function is used to avoid the global
pollution
Only one time we should call the function
Syntax: (function declaration)( function call)
6. Higher order function:
 function which takes another function as an argument is called as higher order function
 HOF can be arrow function, named function, function with expression
7. callback function: the function which you are passing as an argument to higher order
function Is called as callback function
8. nested function:
Function which is declared inside another function is called as nested function

Closure: closure is the scope or memory allocation which gets created when we access the
outer function variable inside inner function then the closure is created for outer function.

Lexical scoping or scope chaining:


It is an ability of function scope to search for the variable till it reaches the global scope this
process is called as Lexical scoping or scope chaining.

Variable hoisting:
Moving variable declaration to the top of the scope is called as Variable hoisting
If we tried to access var variable before variable declaration and initialization it will return
undefined and in case of let and const it will throws uncaught referenceError this Is because of
temporal dead zone(TDZ)

Temporal dead zone(TDZ):


it refers to period between when the variable is declared (let and const) and when it initialized
during this period the variable cannot be access or used even though it is hoisted at the top of
the scope.
If we try to use the variable between this period it will throws reference error.

Function hoisting:
Moving Function declaration to the top of the scope is called as Function hoisting.
It is only applicable in case of named function.
We can call the function before the function declaration if it is named function.

Window object
Window is the super most object in JavaScript
window refers to browser window and it is having the information about the browser
the properties and methods which is present inside window object can be access directly without using object
name.
if we declare any variable with var keyword it will getting stored inside the window object.
Window is used to access the global scope variable inside the local scope.
Globally this keyword refers to the window object

Array
1. arrays are a non-primitive datatype in javascript and it is used to store multiple values or data which can
be any data type
2. array length is not fixed
3. to fetch length of the array we can use length property
4. array is indexed data structure and the indexed position always start from 0
5. we can iterate the array using indexed position
6. we can create the array in three ways
1. literal way
2. using array constructor
3. using Array.of()
note: in array constructor if we pass one argument that is number datatype it will considerd as length
of the array.
And in Array.of() it will consider as the element,
we can add the array element and delete, update fetch array element using the indexed position

1. Array.isArray(): it is used to check whether the data is array or not if it is array it will return true otherwise
it will return false
Note: the datatype of array is object

Array non-static method


1. push(): is used to add the array element at the end of the array and returns the new length of the array
it will take multiple argument so that we can add multiple array elements
2. unshift(): it behave exactly like push() but it will add the array element at the beginning of the array
3. pop(): is used to remove the array element at the end of the array and only one array we can remove
and it will return the deleted array element
4. shift(): this method also exactly behaves like pop()
5. slice(): it is used to extract the part of the array and return in the new array
6. splice(): it is used to add and delete the array element at the particular index position and it will return
the array which contains delete array elements as well as make changes in existing array
7. concat(): it is used to merge 2 or more array and it will not affect the original array
8. reverse(): it is used to reverse the array and it will affect the original array
9. fill():Changes all array elements from start to end index to a static `value` and returns the modified
array
 first param: the value
 second param: start index
 third param: end index -1
10. indexOf():Returns the index of the first occurrence of a value in an array if it is not present returns -1.
Optional second param: The array index at which to begin the search
11. flat(): to convert multidimensional array into a single dimensional
12. join(“”): join the array element by the separator

Array HOF
1. find(): Returns the value of the first element in the array where predicate HOF is true, otherwise undefined
example : ar.find((value, index, array)=>{})
2. findIndex(): Returns the index of the first element in the array where predicate is true otherwise -1
ar.findIndex((value, index, array)=>{})
3. filter(): Returns the elements of an array that meet the condition specified and return new array
ar.filter((value, index, array)=>{})
4. map(): iterate and transform each element of the array and return new array
ar.map((value, index, array)=>{})
5. some(): return true when any of the condition is satisfied otherwise false
6. every(): return true if all the conditions are satisfied otherwise false
7. forEach(): Performs the specified action for each element in an array.
Return type is void
ar.forEach ((value, index, array)=>{})
8. reduce(): reduce or we can say give result as a single output
example: ar.reduce((accumulator, current_value) => acc + cv, intial_value (optional))
9. reduceRight():same as reduce but operation start from right side or give result as a single output
example: ar.reduceRight((accumulator, current_value) => acc + cv, intial_value (optional))
10. includes(): determines whether an array includes a certain element, returning true or false
11. sort(): a negative value if the first argument is less than the second argument, zero if they're equal, and a
positive value if second argument is lesser. the elements are sorted in ascending, ASCII character order.
String methods

Does not modify the original string.

concat()
 Syntax: str.concat(string1, string2, ...)
 Uses: Joins multiple strings together into a single string.
trim()
 Syntax: str.trim()
 Uses: Removes whitespace from both the beginning and end of the string.
trimStart()
 Syntax: str.trimStart() (also known as trimLeft())
 Uses: Removes whitespace only from the beginning of the string.
trimEnd()
 Syntax: str.trimEnd() (also known as trimRight())
 Uses: Removes whitespace only from the end of the string.
toUpperCase()
 Syntax: str.toUpperCase()
 Uses: Converts all characters in the string to uppercase.
toLowerCase()
 Syntax: str.toLowerCase()
 Uses: Converts all characters in the string to lowercase.
slice()
 Uses: Extracts part of a string and returns it as a new string.
 Returns: Returns a new string, does not modify the original.
substring()
 Uses: Returns a substring between two specified indices.
 Returns: Returns a new string, does not modify the original.
substr()
 Uses: Returns a substring starting from a specific index with a given length.
 Returns: Returns a new string, does not modify the original.
charAt()
 Uses: Returns the character at a specified index.
 Returns: Returns a new string, does not modify the original.
charCodeAt()
 Uses: Returns the Unicode value of the character at the specified index.
 Returns: Returns a number, does not modify the original string.
replaceAll()
 Uses: Replaces all occurrences of a substring with another substring.
 Returns: Returns a new string, does not modify the original string.

includes()
 Uses: Determines whether a string contains a specific sequence of characters.
 Returns: Returns a boolean, does not modify the original string.
indexOf()
 Uses: Returns the index of the first occurrence of a substring, or -1 if not found.
 Returns: Returns a number, does not modify the original string.
lastIndexOf()
 Uses: Returns the index of the last occurrence of a substring within a string.
 Returns: Returns a number, does not modify the original string.

Object
1. Object is a non-primitive datatype in javascript
2. Object is used to store the data in the form of key-value pair, and the key should be unique
but the values can be duplicate and it can be any datatype
3. Object is not iterable because it is not an indexed data structure
4. All the keys in the object will be stored internally in the form of string
5. We can access the values from the object in 2 ways
1. Using dot notation
2. Using bracket notation
Example syntax:
const std = {
name: "anis shah",
id: 1,
skills: ["java", "spring"],
id: 5,
address: {
pincode: 421203,
location: "thane",
},
job:"software dev"
};
We can also add, delete, update the values which is present inside the object
Note:
1. object keys should be unique if the same key is passed again then the value will gets
updated
2. If we try to access the value by using key which is not present inside the object it will
return undefined

We can create object in 4 ways


1. Literal way
2. Using class and constructor
3. Using constructor function
4. By using object constructor

class:
class is a blueprint to create the object
we can also define properties and methods inside the class

constructor:
constructor is a special type of method we can also pass parameters and arguments but
constructor does not have any return statement
constructor can be invoked by using new keyword
syntax:
let e1= new Employee(arg1,arg2,………..)

constructor is created using constructor keyword and it is used to initialize the values for the
keys
inside constructor this keyword reference to current creating object

static and non-static members in class


we can create static methods and static properties by using static keyword and static members
can be access with the help of class name
non static members can be access by using object reference

note:
1. if we want to create object and also, we want to define any properties and methods then
we can use class and constructor but the requirement is only limited to creating the object
then we can use constructor function
2. only syntax will be difference in case of class constructor and constructor function

Why primitive datatypes are immutable and non-primitive datatypes are mutable?
 If we try to change any primitive data in the heap area the updated value will gets
changed in the different object address
 But in case of no primitive datatype if try to change the value the updated value will gets
changed in the same object address that’s why primitive datatypes are immutable and
non-primitive datatypes are mutable

Note: if we compare two primitive datatype values it will compare the data not the object
address but in case of non-primitive datatype it will compare the object address that’s why if
we compare 2 objects having same key and value it will return false.

Note 2: const keyword will prevent the values which is trying to store in different object address but we can change
the values within the same object address if variable declared with const keyword that’s why in case of non-primitive
datatype like array and object if the variable is declared with const keyword also we can change the values.

rest parameter
rest parameter is used to store rest of the argument values in a single parameter
rest parameter should be present last in the parameter list of function declaration
example:
function demo(x, y, ...z) {
console.log(x, y);
console.log(z);
}
demo(10, 20, 30, 40, 50, 60, 70);

the rest of the argument values will be stored in the form of array

spread operator
spread operator is used to spread the values for the data types whose are iterable(mostly we
will use for string and array)
example:
let ar = [10, 20, 30, 40, 50];
console.log(...ar);

Destructuring
Destructuring is pattern to pass unique identifiers for the array elements and the object
elements
There are 2 types:
1. Array Destructuring
2. Object Destructuring

Array Destructuring:
Syntax:
const ar = [10, 20, 30, 40, 50, 60, 70, 80];
var [a, b, ...c] = ar;

1. array Destructuring follows order or sequence and we can pass any identifier
2. we can also store multiple array elements using rest element and it should be defined at the last

Object Destructuring:
Syntax:
let obj = {
name: "anis",
id: 200,
skills: ["js", "react"],
percentage: 80,
address: {
pinCode: 421204,
location: "thane",
},
};
let { name, id: eId, fn, ...rest } = obj;

1. in object destructuring we can destructuring we can destructure without following the


order
2. but the identifier should be equal to the key
3. we can also change the identifier by using colon
4. we can also store rest of the object values using rest element and it should be defined at
the last
5. if we destrcuture any element which is not present inside the object it will return undefined

Synchronous behavior
1. synchronous code is executed in a sequence. it means one operation must complete before the next operation
begins
2. if a task takes long time, then the browser is locked and the user must wait until the task finishes

Asynchronous behavior

1. Asynchronous allows code task to run in background will other code is executed
2. Some of the examples for Asynchronous are fetching a data from the server dom events and timers

setTimeOut() & setInterval():

1. Both the functions are used to perform the Asynchronous operation in javascript
2. only one difference between this function that is setTimeout() will execute some set of code after time delay only
once but setInterval() will execute again and again after a time delay
3. both the functions will take 2 or multiple arguments
4. first arg is time handler function and this function will execute after a time delay
5. second arg is time delay in milliseconds
6. and rest of the arg we can pass as the value for parameters for the time handler function
7. both setTimeOut() and setInterval() are present inside window object
8. both the methods will return unique number which is used to stop setTimeOut() and setInterval() functions
9. to stop the setTimeOut() we can use clearTImeOut()
10. to stop the setInterval() we use clearInterval()
11. both the method will take 1 arg that is unique number or id

note: if we are passing same time delay for 2 setTimeOut() or setInterval() functions it will execute based on the order
or sequence

This Keyword
1. Globally  Window Object
2. Inside the Function (Except Arrow Function)
a. With using “use strict”  undefined
b. Without using “use strict”  window object
3. Arrow function anywhere  parent scope this keyword value
4. Inside constructor  current creating object
5. Inside object (literal way)
a. Inside normal function (named function)current object
b. Arrow function  parent scope this keyword value
6. In addEventListner function
a. Anonymous function  targeted object
b. Arrow function  parent scope this keyword value

JSON(JAVASCRIPT OBJECT NOTATION)


 Json is a file format which is used to store the data in the form of array or Object
 In Json file object keys must be double quoted
 Json is lightweight form of storing a data later we can transfer the data to the server or we can receive the data
from the server
 There are two static methods in json
o JSON.stringify(objRef):
 it is used to convert javascript object into json string
 it will take one argument that is object reference
o JSON.parse()
 It used to convert json string into javascript object
 It will take one argument that is json string reference

call(),apply(),bind() -> important


 All the three methods are used to set the value for this keyword inside the function(except arrow function)
 call() and apply() will set the value for this keyword inside the function and also it will execute the function
 bind() will only set the value for this keyword and it will not execute the function and it will return the bound
function(same function) and we can call a bound function
 the difference between call() and apply() is call() will take multiple arguments and apply() will take only two
arguments and second argument is argArray
 call() syntax:
o fn_name.call(obj_ref, arg1, arg2,……..)
 apply() syntax:
o fn_name.apply(obj_ref, [arg1, arg2,…….])
 bind() syntax:
o fn_name.bind(obj_ref)

shallow copy:
1. if we make copy of an object and if we try to change any value in the original object it
will affect the copied object also this way of copying the object is called as shallow copy.
2. We can create the shallow copy of an object in 4 ways
a. By copying object reference:
If we make shallow coping of an object by coping the object reference then it
means we are copying the object address so any changes made in the original
object will affect the copied object also(both primitive and non-primitive values)
b. Using object.assign()
c. Using spread operator
d. Using for in loop
In all the above cases we are not coping the object address so if we make any
changes in original object [primitive value] it will not affect the copied object because
both object address are different
But we make any changes in non-primitive values int the original object it will affect
the copied object also
Deep Copy:
If we make any changes in original object it will not affect the copied object also(both primitive
and non-primitive values)
We can create deep copy of an object in 2 ways
1. Using stringify() and parse()
2. Using structuredClone()
DOM-Document object model
Dom is a tree like structure and by using dom we can manipulate html elements using javascript that is we can add one
html element, we can create one html element, we can set the attributes for the html element, we can give css for html
element and we can perform interactive animations

When the web page is loaded the dom tree is create for that webpage

We can also pass the events for that html elements using dom

document object:

1. Is present inside window object


2. And document refers to the webpage
3. Within document object we have info related to the webpage and some in built methods and properties
that we can use for html elements
4. Entire dom concept we can execute only in browser side

Methods in dom

1. document.getElementById: it is used to target the html element with the help of id and this method will take an
argument as id value (“string”). This method will return targeted html element or null

2. document.getElementsByClassName: it will return HTMLColleciton of all the elements which are having the same class
name that we pass as an argument. It is used to target html elements by using class name and it will take one argument
as class name (string)

3. document.getElementsByTagName: this method also will return the htmlcollection of all the elements which are
having the same tag name that you are passing as an argument. it will take one argument as tag name (string). If tag
name is not present inside the html file it will return empty htmlcollection

4. document.querySelector: it is used to target html element with the help of id, class, tag name selectors. It will target
the first element which is having the Id, class, tag name that we are passing as an argument

5. document.querySelectorAll: it will return the nodelist of all html elements which are having id, class, tag name. using
this method we can target html element by id, class, tag name selectors. If the elements are not there in the html file it
will return the nodelist of length of 0 (empty nodelist)

6. document.createElement: it is used to create the html element based on argument we are passing

7. appendChild: it is used to make only one html element as a child of another html element

Syntax: parentElement.appendChildchildElement)

8. append: it is used to make multiple elements as a child of another html element

Syntax: parentElement.appendChild(……childElements)

9. htmlCollection and nodelist: both are array like objects and it is having a indexed data structure that is we can able to
iterate both. We can also convert both into array with the help of Array.from(), using spread operator […htmlCollection
or …nodelist], Array.prototype.slice.call(). Only one difference between htmlcollection and nodelist that is we can use
forEach() for nodelist and htmlcollection will not support forEach()

10. style: it is used to give css style html elements

Syntax : targetedelement.style.cssProperty=”value”;
11. innerTEXT: using innerText we can pass the textcontent to the html elements

Syntax : targetedelement.innerTEXT =”text content”;

12. innerHTML: using innerHTML we can pass the Text content also we can pass the children for the html elements
13. Syntax : targetedelement. innerHTML =”text content or children”;

MAP:

1. A map object is used to store the data in the form of key and value pair
2. And keys can be any datatype including objects, function, array, and primitive datatypes
3. To create map object we should invoke map constructor
4. Syntax: let m = new Map();
5. It follows insertion order of keys
6. Map having methods like set, get , has, delete, clear and size property

Set:

1. Set object is used to store unique values and it does not store key value pair but rather it stores only unique
values
2. Set object has methods like add, has, delete, clear, and size property
3. Set also follows insertion order of values

Attribute methods in DOM:

1. setAttribute():
a. it is used to set the attribute to the html element it will take 2 arguments first attribute name and second
is attribute value
b. if the attribute is having only attribute name then second argument value should be null or empty string
c. return type is void
2. getAttribute():
a. it will take one argument that is attribute name based on that it will return attribute value in the form of
string and the attribute if attribute is not present it will return null
3. removeAttribute():
a. it will take one argument that is attribute name based on that it will remove the attribute value
b. return type is void
4. hasAttribute():
a. it will take one argument as attribute name and it will return true if attribute is present or it will return
false

classList property and methods:

1. add():
a. it is used to add multiple class names for the html element and it will take multiple arguments that is
class names
2. remove()
a. it is used to remove one or multiple class names based on the argument we are passing
b. and it will take multiple arguments that is class names
3. contains():
a. it will take one argument that is class name
b. it will return true if class name is present or it will return false
4. toggle():
a. it will take one argument that is class name and if the class name is present in the html element it will
remove the class name and return false
b. and if class name is not present it will add and return true

DOM event (Asynchronous):

events are the action which is performed on the HTML elements that happen in web browser and can be detected by
javscript

Types of Events:

we have multiple events in javascript such as click event, mouse event (mouseover,mouseout), keyword
event(keyup,keydown,keypress), form events (submit, focus, change, input), window events (scroll,resize)

how to handle the event in javascript?

There are 3 ways we can handle the events


1. using event handler property
 syntax: targetedElement.eventHandlerProperty = function(){};
 this function is called eventHandler function this will execute if the event is triggered
 this function will take one parameter that is event object and it holds information about the
events
2. using addEventListener() method
 this method will take 3 arguments
 1st is event type
 2nd is event handler function
 3rd is Boolean value (optional) and default value will be false
3. Using HTML eventAttributes
 We can also handle the event using attributes such as onclick, onsubmit, onmouseover,
onmouseout, etc, . and this attributes will take function call as a value and it should be within
double quotes but the function should be declared inside js

Keyboard event
1. keyup : this event will gets triggered when you release the key and it will accepts all the keys
2. keydown : this event will gets triggered when you start pressing the key and it will accepts all the keys
3. keypress : this event will gets triggered when you start pressing the key and it will accepts or allowed only
character key (also ENTER)

for all the 3 events event object will return KeybordEvent object

for mouseover and mouseout event event object value is MouseEvent object

for click event event object value is PointerEvent


form events
1. submit event: it will triggered when u submit the form and submit event should be passed to form tag
2. event.preventDefault(): this method will prevents default behavior of the html elements when the event is
triggered and the return type is void
3. value property: this property is used to fetch the value from the input field
syntax : targetElemet.value;
4. input event: it will trigger every time the value of an input element changes
it will works on input tag, textarea, and select tag.
5. change event: it triggers when the user leaves the input field or finishes select an option in select tag

FormData object
1. we can fetch each and every data from the form by creating FormData object

Object.fromEntries()
This method is used to convert FormData object into javascript object
getAll():
it is a non static method which is present inside ForData object it is used in the checkbox to
fetch all the values and it will return in the form of array
it will take one argument that is name attribute of checkbox
document.getElementsByName():
this method is used to fetch all the HTML elements using name attribute and it will return in
the form of nodeList
checked property :
this property mostly used in radio or check box to check whether the option is select or not
and it will return true if the option is selected otherwise it will return false
Event Propagation
it is concept where we will discuss about how events Propagation through of the DOM tree to
achieve its target and what happens after that
there are 3 phases in event Propagation
1. capturing phase(before achieving its target)true
2. target phase(once it reaches the target)
3. bubbling phase(after achieving its target)false

if we trigger any event it always start from the document object and it will propagates through
child elements to achieve its target and after it will reaches to the document again

the third argument in addEventListner() is Boolean value which decides the element should be
in capturing or in bubbling phase if it is true capturing phase if it is false then bubbling phase
the default value will be false.

e.eventPhase property
this property will return 1 if HTML element is in capturing phase and 2 if it is in target phase
and 3 for bubbling phase

event.stopPropagation():
this method stop the further propagation once I reaches the target
event.stopImmediatePropagation():
this method stop further propagation once it reaches the target and also it will not execute any
other events which is given to the same HTML elements

Promise
Promise is used to handle the Asynchronous operations in javascript
To create Promise object we should invoke the Promise constructor
In javascript Promise will be used mostly while fetching the data from the server through API
URL
Promise having 3 states
1. resolved or fulfilled (the operation completed successfully)
2. rejected (the operation failed)
3. pending (initial state that is neither fulfilled nor rejected)

Executor Function
Syntax :- let promise = new Promise(function (resolve, reject) {
let isDataFetched = false;
if (isDataFetched) resolve("promise is resolved");
else reject("promise is rejected");
});

During constructor call Promise constructor will take one argument that is executor function where we can
write the logic for resolved or rejected state
This executor function will take 2 parameters first is resolve() , second is reject()
If we call the resolve() the promise is in resolve state or if we call reject() function promise is in rejected state

This resolve and reject function will take one argument that is promiseResult if we are not passing
any argument the promise result will be undefined
If we are not calling resolve and reject functions then promise will be in pending state
Promise Instance Methods

1. then()
2. catch()
3. finally()
all the 3 methods are used to handle the error in the promise
all the 3 methods will take one argument that is callback function
then() call back function will execute if the promise is resolved and it will take one parameter
as promiseResult
catch() call back function will execute when promise is rejected and it will take one parameter
as promiseResult
finally() call back function will execute if the promise is resolve or rejected and it will not
execute if the promise is pending

Promise static methods:


1. Promise.resolve():
It is used to create the resolved promise
It will take one argument that is promise result
2. Promise.reject():
It is used to create the rejected promise and it will take one argument that is promise
result (reason)

Window.fetch():
fetch method is present inside window object
It is used to fetch the data from the json file or the api (usually in api the data will be stored in
the form of json object or array of json object)
We can also add, delete, update the data in json file or api
fetch() always return a promise and the promise result will be a Response object
Response object
It holds the information about the data fetching like status text, status code, url , etc.
fetch() will take one argument that is api url or json file path (String)

.json()
It is used to fetch the data or extract the data from the response object
And while extracting it will return the In the form of javascript object

Note: we can also handle the promise only with then method by passing two arguments that is
functions
First argument function will get execute when promise is in resolved state and second
argument will get execute when promise is in rejected state

async function:
1. async function is used to perform the Asynchronous Operations in javascript
2. async function should prefixed with async keyword before function declaration
3. async function always returns one Promise
a. resolve(If function execution is completed)
b. reject(if any error occurs)
4. async function should call with the function name
5. we can return any data within the async function and this will be the PromiseResult if we
are not returning any value PromiseResult will be undefined

handling errors in async function


1. try & catch block
we can handle error within async function using try & catch block within the try block we have
to write the code which we want to execute we any error occurs within the try block code it
will immediately execute catch block
catch block will take one parameter that is error
we can pass finally block also after the catch block and this will execute if error is present also
if there is no error

2. using then() catch() finally():


async function will return promise and we can handle the error with the help of this promise
also using then() catch() finally()
if promise is resolved then return value inside the function will become the PromiseResult
if promise is rejected then the error will be the PromiseResult

await operator
1. await keyword must be prefix with promise
2. it must be used inside async function
3. await keyword waits for the promise to getting resolve or rejected then only it will
executes the rest of the code before it will execute all the synchronous code
4. without await operator we could not able to perform any asynchronous operations
inside async function
fetch() using async function
fetch() will return one promise and if it is prefix with await keyword directly it will return the
PromiseResult

JS Modules:
Modules are used to import and export the data from one js file to another js file.
There are two types
1. commonJs module
2. ES6 Module

1. Common js :
 It works only on the server side
 To export the data we can use module.exports() and we can pass the data in the form of
object
 To import the data we can use require() and it will take one arguments as js file path and
require() returns the imported data in the form of object
2. ES6 Module
 It works only on the browser or client side
 There are two type of ES6 module
i. default export
ii. named export
 in ES6 module we should use the extension .mjs and also when make the connection
between HTML and js file we should pass the type=”module” in the script tag

a. default export :
1. we can export only one data
2. and the exports syntax: exports default identifier
3. when importing the data we should use the syntax import identifier from
“file path”;
4. when importing the data we can use any identifier
5. while
b. named export:
1. we can export multiple data
2. and the export stmts syntax pass export keyword followed by data
3. export function(){}
4. when importing the data we should pass the same identifier and the import
stmts syntax : import { identifier } from “js file path”.
5. We can also change the identifier during import but using “as” keyword
JS ENGINE
1. Js engine is the execution unit of browser and it is responsible for the code execution in
client side
2. Js engine is the software component that interprets and executes javascript code
3. And js engine will be present in each and every browsers

Browser JS Engine
Chrome  V8
Safari  JS core
Firefox  spider monkey
IE(Edge)  chakra

Javascript engine frist performs lexical analysis and scanning with within the parser where it
reach the source code separate the tokens or groups the tokens like identifiers, keywords,
operators
Next step in parser is syntax analysis where it checks syntax error
after this step the engine parser the token into abstract syntax tree which represents the
syntax representation of the code
abstract syntax tree:
it is a hierarchical tree like structure that represents the relationship between different parts of
the code such as statements , expressions and operator
after the result of AST the interpreter checks the code line by line and generate the byte code
in some modern browsers like chrome there will be one more step that is Just in time
compilation to optimize the code
after compilation and optimization the jscode will get executed during execution the engine
manages the callstack which keeps track of the function call and context (local variable)
Generator Function
in generator function we can pause the code execution using yield keyword
generator function always return generator object with suspended or closed state
if function execution completed then closed state and if not completed then suspended state
we can call the generator function using next method And it will executes till the yield
statement and returns the yeild value in the form of object
syntax:
function* fun_name(){}
if we have n number of yield statements inside function then we should use n+1 next method
we can the next() by using generator object reference
we can also return any values using return statement but it should be present at the last but
only one return statement will be allowed

You might also like