JAVASCRIP Notes
JAVASCRIP Notes
- 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:
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...
------------------------------------------------------------
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.
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
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
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.
- 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
- 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)
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)
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)
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)
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'
}
-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:
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.
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.
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
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.
2. FUNCTION EXPRESSION
Syntax : var/let/const identifer = function (){}
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.
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.
}
}
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.
-----------------------------------------------------------
ARROW FUNCTION:
(parameters_list....)=>expressions
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:
(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:
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;
});
- 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:
synatx:
...identifer
uses of rest parameter:
1. rest parameter can be used in function defination parameter list to accept multiple values.
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.
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.
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();
Ex:
//function construction
function Student(sid,sname){
this.sid=sid;
this.sname=sname;
}
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.
2. Object.values()
-> It is static methods returns an array of a given object's own enumerable string-keyed property
values.
3. Object.entires()
-> It is static methods returns an array of given object's own enumerable both string-keys and
property values.
------------------------------------------------
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
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.
DOCUMENT
|
|
HTML
-----------------
| |
| |
HEAD BODY
| |
| |
---------- ------------
| | | |
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)]
<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>
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>
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 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.
Note:
- Event object can be used only inside the eventHandler
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'
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")})
}
- To achive the above said scenario we can the use the following design technique:
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().
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