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

JAVASCRIP Notes

Uploaded by

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

JAVASCRIP Notes

Uploaded by

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

==========================JAVASCRIPT==========================

- JS is High Level Language.


- JS is programming language.
- Browser: it is an application which provides environment to run JS instruction from HLL to MLL.
- JS cade can run both inside and outside the browser.
- Inside browser is JS engine and Outside browser is Node JS engine.

- Node: it is the combination of the c++ and V8(chrome JS engine) with bundle of methods and
rule.
Node provide environment to run JS outside the browser. This invetion help the JS to
gain the popularity in usage as a backend language.
- We can run JS both inside and outside the browser.

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

CHARACTERISTICS OF JAVASCRIPT:

1. Purely object based.


2. Interpreted language.
3. Synchronous(coz,it follows the SINGLE threaded arechitecture which has only one stack)
4. Both client and server sided.

Note:
- object: it is block of memory which has state(variable) and behaviours(function).
- console.log(argument); here,console is a object, dot is a period or access operator and log is a
function and member of console that accepts arugment as data to print in console.

To execute JS on browser:

1. We can execute the js instructions directly in the console provided by the browser.
2. We can execute js instructions by embedding it in html page.
types:
1. Internal JS
2. External JS

1. Internal JS:
with the help of script tag, we can embedd js instructions.
Syntax:
html code ...
<script>
js code
</scrpit>
2. External JS:
a. we can create a separate file for js with a extension .js
b. link the js file with html [age using src attribute of script tag].
syntax:
html code...
<script src="path/filename.js">(if js file and html file in the same
folder path is not required)
js code...
<script>
html code...

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

TOKEN: smallest unit of any programming language. And consist of


1. Keywords: a pre defined reserved word which understandable by the js engine is known as
keyword.
Note: every keyword must be in the lower case and is not used as identifiers. Ex: if, for, let,
const, while, do-while, null, switch

2. Identifiers: name given by the programmers to the components of js like variables, functions,
class etc are known as identifiers.
Rules for identifiers:
- an identifier can't start with number.
- except $ and _ no other special characters are allowed.
- we can not use keywords as identifiers.

3. Literals/Values: data which is used in the js program is called as literals/values.


Types of values in js:
- Number
- String
- Boolean
- Null
- undefined
- object(non-permitive)
- Bigint
- symbol

VARIABLES:
A named block of memory which is used to store a value is known as variables(container to
store data)

Note:
- in js variable are not strictly typed, it is dynamically typed. Therefore it is not necessary to
specify type of data during variable declarations.
- in a variable we can sotre any type of value.
- it is mandatory to declare a variable before using.
- Data type of NaN is Number

-syntax: var/let/const identifier;

ex:
var a ;//declaration
a = 10 ;//initialization or assignment
console.log(a); //10

let b ;
b= 10;
console.log(b); //10

const c =30;
console.log(c); //30

Note: when a variable is declared in js, js engine implicitly assigns undefined value of it.
ex:
var a;
console.log(a); //undefined

UNDERSTANDING EXECUTION IN JS:


1. everytime when js engine runs a js code, it will 1st create a 'global execution context'.
2. The Global execution context has 2 part:
a. variable area.
b. Execution area.
3. JS engine generally uses 2 phases to execute a js code.

phase 1: All the memory is allocated for the declaration in top to bottom order and assigned with
the default value 'undefined' in variable area of gobal execution context.
phase 2: All the instruction get executed in the top to bottom order in execution area of gobal
execution context.

Ex: trace the following code


clg(a)
clg(b)
var a
a=10
clg(a)
var b = 20
clg(b)

TRACING OF ABOVE CODE: (for diagran refer notes).


1. creation of gobal execution context.
2. In the variable area, only variable declaration are stored.
3. for clg(a); //undefined. coz, by default for var a, it is "undefined". similarly for clg(b)
4. for clg(a); //10, coz the default value "undefined" is replaced by 10. similarly for clg(b). It
happens in the execution/functional area.
5. so, the js interpreter scans the js code 2 time. once for variable area and another one for
execution area.

HOISTING: JS allows a programmer to use a member (variable) before the declaration


statement. This characteristic is known as hoisting.

- variable hoisting is only supported by "var" where as "let" and "const" does't support variable
hoisting

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

STRING
- In js string can be represented using single quote, double quotes or backticks.

Note:
- The start and end of a string must be done with the help of same quotes.
- If a text contains single quote then it can be represented using double quotes.

Ex:
text: I'm a developer
in js: "I'm a developer"

Backtick:
A backtick can be multiline String.
Ex:
var hobbies = `My hobbies are:
1. football
2. cricket
3. movie1`;
console.log(hobbies);

Note:
- the string represented using backticks is also know as template string. The advantage of it is
we can substitute and express it using ${}.
Reverse String:
let str = "HELLO"
console.log(str.split('').reverse().join(''))

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

Arrays

- It is collection of homogenous (similar data type) and hetrogenous(different data type)


elements.
- Represtation of arrays is []

ex: let arr = ["hi",0,true,undefined,null,{}]

- in the above example insider arr variable we have store all the data types, it supports all the
data type.

Array methods:

1. pop():
- it is a method which is used to delete the last element of an array
- Ex: let arr = [10,20,30,40,50]
arr.pop()
console.log(arr)

output: [10,20,30,40] last element 50 has been deleted

2. push():
- it is a method which is used to add the element at last index
- Ex: let arr = [10,20,30,40,50]
arr.push(100)
console.log(arr)

output: [10,20,30,40,50,100] last element 100 has been added

3. shift():
- it is a method which is used to delete the first element of an array
- Ex: let arr = [10,20,30,40,50]
arr.shift()
console.log(arr) //[20,30,40,50]

4. unshift():
- it is method which is used to add the element at first index
- Ex: let arr = [10,20,30,40,50]
arr.unshift(100)
console.log(arr)

output: [100,10,20,30,40,50] 100 has been to the first index.

5. concat():
- this method is used to merge multiple arrays into one single array
- syntax: a.concat(arrays to be merged with a)
- Ex let a = [10,20,30,40,50]
let b = [60,70,80,90,100]
let c = ['a','b','c','d']

let d = a.concat(b,c)
console.log(d) //[10,20,30,40,50,60,70,80,90,100,'a','b','c','d']

6. splice():
- it is a method used to add and delete the element at the same time
- splice method affects original array
- it will accept three argument.
- syntax: splice(start index, count of element to be deleted, which element to be added)
- Ex: let a = [10,20,30,40,50]
a.splice(1,2,100)
console.log(a)

output: [10,100,40,50]

7. slice():
- it is methods which is used to take out sliced elements from the original array
- it will not affect the original array
- end index will always be ignored
- syntax: slice(start index, end index)
- Ex: let a = [10,20,30,40,50]
let b = a.slice(1,2)
console.log(b)

output: [20]

8. includes():
- it is a method used to check whatever the element is present inside an array or not
- include will always return "boolean value"
- syntax: a.includes(element which you wanted to check)
- Ex: let a = [10,20,30,40,50]
console.log(a.include(10)) // true 10 is present

9. indexof():
- it is used to check the index of a value of particular element
- indexof will retuerns "indexvalue" of an array
- syntax: a.indexof(element which you wanted to know the index value)
- Ex: let a = [10,20,30,40,50]
console.log(a.indexof(10)) //1 (index value of 10)

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

OBJECT:
- Any subtance which has its existance in the real world is known a object.
- Every object will have properties(attribute of feeds which describe them)
- Every object will have actions(behaviours)

Ex:
1. car:
- properties of car: model,color,price.
- action of car: accelarate,brak,start,stop.

2. webpage:
- properties of webpage: url data/content on webpage.
- actions of webpage: scroll,hover,click.

Note:
- In programming an object is a block of memory which represents a real world.
- The properties of real world object are represented using variables
- In javascript object is collection of attribute and action in the form of key value pair enclosed
with on the curly braces{}
- Key represent the properties and attribute of an object.
- Value represent state of an object.
- In javascript, we can create js object in 3 different ways:
1. object literal{}
2. Using a function
3. Using a class

1.Object literal:
synatx:
let variable = { key1:value1, key2:value2 ....}
- we can access the value of the object with the help of dot operation(period).
Ex:
let eDetails = { -------> 'eDetails' store the address of an object
empId:1480,
empNmae: 'AB'
empSal: '3Lpa'
}
console.log(eDetails)
console.log(eDetails.empName)
console.log(eDetails.empId)
console.log(typeOf eDetails)

Note:
-If the key is not present in the object then we get 'undefined' as the value.

Ex:
let eDetails = { -------> 'eDetails' store the address of an object
empId:1480,
empNmae: 'AB'
empSal: '3Lpa'
}
console.log(eDetails.empAddress) //undefined

Note:
-The object in js are mutable(state of the object can be modified) in nature.
Ex:
const eDetails = { -------> 'eDetails' store the address of an object
empId:1480,
empNmae: 'AB'
empSal: '3Lpa'
}

eDetails.empSal = '3.5Lpa'
console.log(eDetails)

- To add a key Value pair into an object:

syntax:
object_reference.key = value

Note:
- If the key and value is not peresent in the object, it create a new key and value when you
search
Ex:
const eDetails = { -------> 'eDetails' store the address of an object
empId:1480,
empNmae: 'AB'
empSal: '3Lpa'
}

eDetails.empJob = 'Software Developer'


console.log(eDetails)

TO DELETE A KEY FROM AN OBJECT:

-we can remove a key from an object with the help of delete operator.
Syntax:
delete object_reference.key;

Ex:
const eDetails = { -------> 'eDetails' store the address of an object
empId:1480,
empNmae: 'AB'
empSal: '3Lpa'
}
delete eDetails.empSal;
console.log(eDetails);

METHODS OF OBJECTS

1. Object.keys(Object_name)
2. Object.values(Object_name)
3. Object.entires(Object_name)
4. Object.defineProperty(objectName,"keyName",{
writable:false
})// this method is used not to change the value for a particular key
---------------------------------------------------

FUNCTION:

- named block of instructions which is used to perform a specific task.


- Function gets executes only it is called.
- the main advantage of function is, we can achieve code reuseabilty.
- MAIN PURPOSE: code reuseabilty, which means-code once delcared can be anywhere.

Note:
Syntax to create a function :
Generally we can create a function in 2 ways:
1. using function declaration statement(function statement)
2. function experssion.

1. FUNCTION DECLARATION STATEMENT:

function identifer(param1, param2, ...)


{
statement
}

Note:
- function is an object.
- Name of a function is a variable which holds the reference of function object.
- Creating a function using function statement supports function hosting. Therefore we can also
use a function before function declaration.

Ex: console.log("start");
console.log(test);
function test(){
console.log("Hello");
}
console.log("end")
- when we try to log the function name the entire function definition is printed.

-> To call a function.


function_name("argumenet list"); function calling start

PARAMETERS:
- The variable declared in the function defination declaration is known as parameter.
- The parameters have local scope. Those can be used inside the function body.
- Parameters are used to hold the value passed by a calling a function.
Ex:
function sum(a,b){
console.log(a+b)
} (here a and b are variable local to the function sum)

ARGUMENETS:
- The value passed in the function call statement is known as arguments.
- An argumenet can be literal, variable, or an expression which results a value

Ex1: sum(10,20)---10,20 are literal is used as arguments


Ex2: sum(-10+3,-20) //-27
Ex3: let a=20 b=30
sum(a+b) //a&b are variable used a arguments

RETURN:
- It is keyword used as control transfer statement in a function.
- Return will stop the execution of the function and transfers the control along with data to the
caller.

Ex: function toMeter(centimeter){


return (centimeter/100)
}
var cm =2
console.log(toMeter(cm)) //0.02
var m = toMeter(cms);
console.log(m) //0.02

2. FUNCTION EXPRESSION
Syntax : var/let/const identifer = function (){}

- in this syntax the function is used as value.

Disadvantage:
- The funaction is not hoisted, we can not use the function before declaration.
- Reason: Function is not hoisted, instead variable is hoisted and assigned with default value
undefined.
- Therefore typeOf a is not a function,it is undefined. Refer below example.

a(); //error 'a' is not a function

var a = function(){
clg("hi");
}
clg(a); /function start or body is printed
a();
a =10
a(); //error 'a' is not function, coz a is changed to number type from function.

- This we call variable is of dynamic type. I can change variable value during run time.

Note:
Scope w.r.to function:
1. Any member delcared inside a function will have local scope.
LOCAL SCOPE:
- The scope within the function block is known as Local scope.
- Any member with local scope can not be used outside the function block.
Ex:
1. A parameter of a function will have local scope
ex: function test(a){} ---------> here 'a' is the varable whose scope is local to test and it can be
used only inside test function block.

ex2: function test(){


var a; ------> it is local to test function, it can not be used outside.
}

ex3: function test(){


function insideTest(){

}
}
Note: insideTest is function,local to test function and can not be called from outside test()

Note:
- Inside a function we can always use the member of gobal scope.

Ex:
var city = 'bangolre';
function display(name){
console.log(`$(name) belongs to $(city)`)
}
display('sheela');

in the above ex variable name has local scope and var city has gobal scpoe.
It is observed inside function body we can use both the variable name & city.

CLOSURE:
- The closure is a binding of parent function variable with the child function.
- This enable a JS programmer to use parent functions member inside child function.

Ex:
function person(){
let age = 21;
function printAge(){
return age
}
return printAge;
}
let x = person();
console.log(x())

let a = 10
function x(){
let b = 20
function y(){
console.log(b)
}
return y
}
let c = x()
console.log(c())

the above ex printAge is nested to function to person() the function printAge() does not declare
any local variable, but still we are able to use age variable which belong to person this is
achived with the help of closure.

Note:
The binding of child/inner/nested function with its lexical environment(parent function state) is
known as closure.

points to remember on closure:


- closure helps to achive scope chain(lexical environment) from child function to parent function.
- closure preserves the state of parent function even after the execution of the parent function is
completed.
- A child function will have reference to the closure.
- Every a parent function which has called function is called( parent function call) a new closure
is created.

Disadvantage of closure: High memory consumption.

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

ARROW FUNCTION:

- Arrow function was introduced from es-6 version of javascript.


- Synatx:
(parameter list,......) => {}
- Arrow function can have 2 type of return:
1. implicit retrun: using 'return' keyword is not required.
synatx:

(parameters_list....)=>expressions

EX: let x = () => "HI"

2. explicit return: using 'return' keyword is mandatory with curly brackets{}, if 'return' keyword is
not used 'undefined' is given back.
- If a block is created an arrow function behave like explicit return
syntax:
(parameters_list...)=>{return expressions}

Ex: let x=(a,b)=>{


return a+b
}
Note:
- parameter are optinal
- If the function has only statement, then block is optinal.
- It is mandatory to create a if 'return' keyword is used.

Ex:
(a,b) => return a+b ----------> synatx error, unexpected token 'return'
(a,b) => {return a+b} --------> solution 1 or
(a,b) => a+b; ---------> solution 2

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

CALLBACK Function:

- Passing a function as an argument to another function is known as callback function.

Advantage:
-> Instead of creating a function with a specific task, functional programming helps programmer
to generate function which can perform a generic task by accepting as argument.

Ex:
function operation(a,b,task){
let res = task(a,b);
return res;
}
let res1 = operation(10,20,function(a,b){
return a+b;
});

let res2 = operation(30,20,function(a,b){


return a-b
});

let res3 = operation(30,20,function(a,b){


return a/b
});
console.log(res1);
console.log(res2);
console.log(res3);

HIGHER ORDER FUNCTION:

- A function which accept another function as an argument is known as higher order function.

Ex:
function add(a,b,task){
console.log(a,b,task)
let value = task(a,b,x)
console.log(value);
}
function y(x,y,task1){
task1()
return x+y
}
function x(){
console.log("I'm X");
}
add(2,2,y)

-------------------------------------------------
Rest Parameter:

- rest parameter is used to accept multiple values as array of elements.


- generally it converts multiple value into an array.

synatx:
...identifer
uses of rest parameter:
1. rest parameter can be used in function defination parameter list to accept multiple values.

using rest parameter in a function:


1. the function can recieve multiple arguments passed by the caller and store them in an array.
Ex:
function tets1(a,...b){
console.log(a);//10
console.log(b);//[20,30]
}
test1(10,20,30);

Note: rest parameter should be always defined at the last

Ex:
function test1(...a,b){
console.log(a);//10
console.log(b);// syntax error: rest parameter must be last formal parameter
}

SPREAD OPERATOR:

- It is used to perform unpacking, it uses an iterator to access each and every element or a
property in the array or object.
- It can also be used in array an object destructuring.

Ex: 1. For Array

let a = [10,20,30];
console.log(Math.max(...a));//30, using spread operator
console.log(Math.min(...a));//10
console.log(Math.max(a[0],a[1],a[2]));
console.log(Math.max(a));//NaN
console.log(a)

2. For Object

let obj1 = {
id:123,
company:"Google",
salary:"5Lpa"
}
let obj2 = {
name:"AB",
...obj1
}
console.log(obj2);

Math Object:
1. Math.max():
EX: let highValue = Math.max(10,20,52,85,5,10)
console.log(highValue)

2. Math.min():
Ex: let lowValue = Math.min(10,20,52,85,5,10)
console.log(lowValue)

3. Math.round():
Ex: let roundValue = Math.round(10.5)
console.log(roundValue)

4. Math.floor():
Ex: let floorValue = Math.floor(10.3)
console.log(floorValue)

5.Math.ceil():
Ex: let ceilValue = Math.ceil(10.3)
console.log(ceilValue)

TYPE COERCION:
- The process of converting one type of data into another type of data by js engine
implicitly(implicit typecasting), when a wrong
type of data is used in the expression is known as type coercion(or implicit type casting).

Ex:
console.log(10+'20');//1020, number is converted to string
console.log(10-'2');//8, string is converted to number
console.log(5-'a');//NaN, the string does not a have vaild numeric value, hence it is convertes to
a special number 'NaN

What is NaN?
NaN(Not a Number) is number.

Any arithmetic operation with NaN, result is NaN,


Note:
clg(NaN==NaN) flase

CONSTRUCTOR FUNCTION:

-A function which is used to create an object is known as constructor function

Synatx:
function identifer(parameter,...){

Note:
- If the function is designed to use a constructor then the name of the function should always be
UpperCameClass.
- List of parameter provided to the function will be treated as the keys (properties) of the object.
- The argument passed when the function is called will be the values.
- We can copy the value into the keys of object from parameter using 'this' keyword.
- we can create an object using constructor function with the help of 'new' keyword
- syntax:
new function();

Note : 'new' create the object and returns its reference.

Ex:
//function construction

function Student(sid,sname){
this.sid=sid;
this.sname=sname;
}

let a = new Student(1,"Avaez")


let b = new Student(2,"Basha")

console.log(a);
console.log(b);

--------------------------------------------------
Object Methods:

1. Object.keys()
-> It is static method returns an array of a given object's own enumerable string-keys property
names.

Ex: let a = Object.keys(car1)


console.log(a) // ["name","brand","price"]

2. Object.values()
-> It is static methods returns an array of a given object's own enumerable string-keyed property
values.

Ex: let b = Object.values(car1)


console.log(b);// ["alto","MZ","5Lpa"]

3. Object.entires()
-> It is static methods returns an array of given object's own enumerable both string-keys and
property values.

Ex: let a = Object.entires(car1)


console.log(a); // [["name","alto"],["brand","MZ"],["price","5Lpa"]]

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

LOOPING STATEMENT:

1. ForEach:
-> This method is used to loop through each element of an array this method takes a callback
function as an argument is invoked.
for each element of the array or object.

Ex: arr.forEach((x,y,z)=>{
console.log(x,y,z);
})

2. Map:
-> This method is used to loop through each element of an array this method takes callback
function as an argument.
-> callback function is involved for each element of the array or object
the map() is similar to the forEach() method but it retrun an new array

Ex: let arr=[10,20,30,40]


let final = arr.map((a)=>{
return a
})
console.log(final)
Diff B/W forEach and Map:
1. The map() method returns a new array for but the forEach method does not return a new
array
2. The map() method is used to transform the elements of an array, whereas the forEach()
method is used to loop through the element of array.
3. for of method:
-> The for of method execute a loop that operates on a sequence of values sourced from
an iterable object.

Ex: for(let a of arr){


console.log(a);
}

4. for in method:
-> The for in method is used to return the index values.
Ex: for(let a in arr){
console.log(a);
}

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

DOCUMENT:
- Document is an object created by browser.
- The Document object is the root node of DOM tree.
- To manupulation of data in thre UI.

DOM:
- The every html element is considered as a node(js object) in DOM.
- DOM allows to modify the document content rendred by the browser without reloading the
page. Therefore DOM helps to make a web page
dynamic.

- DOM is an API provided by the browser


- DOM is not javascript,it is bulit using javascript
- DOM is a object oriented representation of html file.
- Every time an html document is given to the browser, it automatically generated
it can be accessed and modified using the root node document in javascript

DOCUMENT

|
|

HTML

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

| |

| |

HEAD BODY

| |

| |

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

| | | |

STYLE TITLE SECTION DIV

DOM selectors or DOM methods


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

1. Document.getElementById():
------------------------------------

- document.getElementById() function targets and return only one particular specified element
based on id value.

Example:

<body>
<h1 id="head"> Hello World</h1>
</body>
<script>
let h1 = document.getElementById("head").innerText
console.log(h1)
</script>

2. document.getElementsByClassName():
-------------------------------------

- The function targets and return all the element with matching class value.
- It return HTML collection object and as to the access to using index value.

Example:
<body>
<h1 class="a">Hello1</h1>
<h1 class="a">Hello2</h1>
<h1 class="a">Hello3</h1>
</body>
<script>
let h1 = document.getElementByClassName("a").innerText
console.log(h1)
</script>

3. document.getElementByTagName():
------------------------------------

- The function is used to target or fetch and element form the document object model
- This function is used to target the element based on the tag a name

Example:
<body>
<h1>Hello1</h1>
<h1>Hello2</h1>
<h1>Hello3</h1>
</body>
<script>
let h1 = document.getElementByTagName("h1")
console.log(h1)
</script>

4. docuemnt.querySelector():
------------------------------------
- Query selector function is used to target an element using tagname, id value, class value.
- In which input avaliable first that is tag name, id value, classValue it retruns the particular
element

Example:
<body>
<h1>Hello1</h1>
<h1 id="c">Hello2</h1>
<h1 class="q">Hello3</h1>
</body>
<script>
let a = document.querySelector("#c")
console.log(a)

let b = document.querySelector(".q")
console.log(b)

let c = document.querySelector("h1")
console.log(c)
</script>

5. document.querySelectorAll()
-----------------------------------------

- Query selector all function is used to target all the element using tagname, id, class.
- It will return all the element in the form of nodeList
- It will return (NodeList[])<== it is an impure array... we can perform only forEach method
- To perform map method first we have to convert it into pure Array
Synatx: ====> Array.from(ele)
- To check array is pure or not [Syntax ==>Array.isArray(variableName)]

---> it will retuen boolean value True/flase


Example:

<body>
<div>Div1</div>
<div id="a">Div2</div>
<div class="b">Div3</div>
</body>
<script>
let div = document.querySelectorAll("div")
console.log(div) // it will return the nodeList
</script>
EVENTS:

- Event is basically an action perform for respective event handler should be attached.
eg: onclick(), onmouseover(), onmouseout(), ondblclick(), onkeydown(), onkeyup(), onchange()
--------

1. onclick(): It is an event in DOM whenever we wanted to perfom some specific task after
clicking a particular element.
target the element which you wanted to click and then use an attribute "onClick" and
assign a function to call it.

Example:
<body>
<button onclick="x()>click</button>
</body>
<script>
function x(){
console.log("Hi")
}
</script>

2. onmouseover(): It is an event where we wanted to perfom task only after when


cursor move in the particular element

Example:
<body>
<button onmouseover="x()">clcik</button>
</body>
<script>
let x=()=>{
console.log("hello")
}
</script>

3. onmouseout(): It is event where we wanted to perfom task only after when cursor moves out
on that particular element.

Example:
<body>
<h1 onmouseout="x()">click</h1>
</body>
<script>
let x=()=>{
console.log("move out")
}
</script>

4. ondblclick(): It is an event where we wanted to perform specific task after double clicking a
particular element.
- targeting the element which you wanted double clcik then we write attribute

Example:
<body>
<button ondblclick="x()">click</button>
</body>
<script>
let x=()=>{
console.log("double click")
}
</script>

5. onkeydown(): It is an event where we wanted to perfom specific task

EVENT:
- Event is an action performed by a end user on a web page.
- A end user can perform different events such as - 1. Mouse events

2. Keybroder events

EVENT LISTENER:
- Event listener/handler is a function which executes task when an event is occured on the most
specific element.

Event flows:
- Event bubbling.
- Event capturing

Event bubbling:
- In event bubbling, the event starts at the target element(most specific element) and then flow
in the upward direction of the DOM tree

Event capturing:
- In event capturing, the event start from the top of the DOM tree (least specific element) & flows
down wards upto the target element(most specific element).

Events propagation:

-Event propagation has 3 phase:


1. Phase I: Event capturing occurs, it provides the oppurtunity to intercept the elements
2. Phase II: Actual target element recieves the event
3. Phase II: Event bubbling occurs, it provide an oppurtunity to have a final response to the
event

Event Object:
- Every event is an object, which is created for an event when event occurs is known as event
object.
- Web browser creates the event object when event occurs.
- The web browser passes the event object to the event handler.

Some of the properties or methods of event object:


1. type: It holds the type of event that is fired!
2. target: It holds the reference of target element of the events
3. eventPhase: It holds the number which represents the event phases
a. capturing phase
b. target
c. bubbling
4. currentTarget : holds the reference of current element on which the event is firing
5. stopPropagation(): It is function, which cancels any further event capturing or bubbling.

Note:
- Event object can be used only inside the eventHandler

To ADD AN EVENT HANDLER TO AN ELEMENT:


- We can add an event handler to an element with the help of addEventListener() methods of
DOM onject

Syntax:
target element.addEventListener(a1,a2,a3);
a1 ----> event as a string
a2 ----> event handler
a3 ----> boolean value

NESTED EVENT:
- If there is an event designed with the same event inside the nested elements then it is known
as nested events.
Ex:
Let us consider nested div tags where each div tag is having an event handler "click"

-----------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|-----------------------------------------------------------------------

case 1:
If event "click" occurs on the grandfather then the event handler of grandfather is executed.

case 2:
when event occurs ont eh parent,
- the target is parent
- all event handlers of both parent and grandfather get executed
- If we use event capturing flow, then event handlers from the top to target gets
executed, therefore the output will be "grandparent clicked" and "parent clicked"
- If event bubbling flow is used, then the execution of event handler from target (bottom)
to top. Therefore the output will be, "parent clicked" then "grandparent clicked"
- By default it follows the bubbling flowduring
PROMISE:
- Promise is an object.
- Promise object keeps an eye on the asynchronous task given
- If the asynchronous task yet not completed, the promise is considered as 'pending'
- If the asynchronous task is successfully completed, then the promise is considered as
'resloved'.
- If the asynchronous task is completed but not successfully, then it is considered as 'reject'
- In promise object we have 2 important methods:
1. then():
- It can accept a caalback function
- The called function passed to the then() methods gets executed only when the
promise returns 'resloved'

2. catch():
- It can accept a callback function
- The callback function given to catch() gets executed only when the promise
returns 'reject'

SYNTAX TO CREATE A PROMISE OBJECT:


new Promise(callback function)
// or
new Promise((reslove,reject=>{
asynchronous_task
}))

Note: therefore, we pass the asynchronous task as callback function to teh promise object.

Ex:
let us consider an asynchronous function printEven()
function printEven(m,n){
//async task
return new Promise((reslove,reject)=>{
setTimeout(()=>{
for(i=m;i<=n;i++){
if(i%2==0){
console.log(i)
}
}
//on successfully
return reslove();
},1000
)
});
}
function successMsg(){
console.log("Number printed successfully")
}
//printEven(10,20).then(successMsg)
printEven(10,20)
.then(successMsg)
.then()
.catch(()=> console.log("Something wrong"))

-assume we have to call printEven() method and execute some dependent task, this is done
using then() method of promise.
function start(){
clg("start")
printEven(10,"20a")
.then(()=>{clg("end")})
.then(()=>{clg("end")})
.catch(()=>{clg("something wrong")})
}

Problems with Asynchronous behaviour:

- If a feature is asynchronous we can not predict when the task is completed.


- Since the completion of asynchronous feature is not predictable, if there is any dependent
feature/task which has to be executedonly after the completion of the asynchronous behaviour,
it become difficult to design.

- To achive the above said scenario we can the use the following design technique:

1. with the help of callbacks


2. Using promises introduced in ES-6

Ex:
function print(m,n){
//async
setTime(()=>{
for(let i=m;i<=n;i++){
console.log(i)
}
},5000)
}

function successMsg(){
console.log("Number printed successfully")
}

- print(m,n) is an asynchronous function, therefore we can not predict when the function will
complete its task.

case1:
console.log("JS Starts")
print(10,15)
successMsg();
console.log("JS ends");

Expectations:
- we expert successMsg() is printed after the completion of print(10,15) method call.

Relity:
-Since print(10,15) is asynchronous it give away the callstack and can not predict when the
number are printed. But the success msg is printed before the number are printed.

Note:
From the above ex we understood successMsg() is dependent on async print() method.
Therefore the above design does not promise us successMsg() to be executed after print().

We can slove these problem using callback:


- The print() must accept dependent function,
- The print() mehtod should take the responsibility of calling the callback function.

Redesigning print() using callback:


Note:
- We can call asynchronous print() method by passing the dependent function as a callback
function.

Ex:
console.log("JS Start")
print(10,15,successMsg)
console.log("JS End")

DESTRUCTURING:

- Destructuring is a covenient way to extract multiple pieces of data from arrays and objects into
distinct variable, making code concise and readable.

Array Destructuring:
- Array destructuring allows unpacking array values into separate variable using square
brackets[], enabling quick and intuitive access to specific elements

You might also like