[Go to site: main page, start]

0% found this document useful (0 votes)
2 views14 pages

JavaScript Basics: Variables, Functions, and DOM

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views14 pages

JavaScript Basics: Variables, Functions, and DOM

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

JavaScript Notes

early name mocha


letter live script
now java script

it is high level multi paradigm object oriented language


it is also synchronous and single threaded behavior
it is the language of web and is used to make web pages and web application work
dynamically

VARIABLES
---------
variables nothing but a block of memory

KEYWORDS IN JS
--------------
var---if we created a it in inside a function it is accessible only inside that
function we cannot use it outside a function....it is function scoped
*we can create same variable using var

let---it is a block scoped because if you created a variable with let it is


particular to that block only inside that curly braces.
*we can not create same variable using let
*it is mutable

const----we cannot change its value it is constant


*it is constant

Example
--------
var b=10;
const a=20;
let c=10;
b=6;
c=8;
[Link](b, a, c);

DATATYPES
---------
1)Primitive data types

Number, string, Boolean, undefined, Null, Big Int

2)Non primitive data types

OPERATORS AND CONDITIONS


------------------------
Unary Operator
1)Pre-Increment/Decrement
++a/--a
2)Post Increment/post decrement
a++/a--
Assignment Operator
=

Comparison operation
>,<,>=,<=

==(Example)
let age=10;
let a="10"
[Link](a==age);//output: true

===(Example)
let age=10;
let a="10"
[Link](a==age);//output: false(correct output)

!=

Ternary operator
Syntax:

(condition)? "val1" : "val2";

Example:
let age=18;

[Link](age>=18?"true":"false");

Logical operator

AND----&&
OR-----||
NOT----!

Falsie
undefined
null
0
false
NaN
' '

truthy
anything which is not falsie

Bitwise Operator

&,|,~,<<,>>,XOR

0000---0
0001---1
0010---2
0011---3
0100---4
0101---5
0110---6
0111---7
CONDITIONAL STATEMENTS
if and else if and else

if(){
//statements
}
else if(){
//statements
}
else{
//statements
}

SWITCH CASE
------------
Syntax:

switch(expression)
{
case 1:
break;
case 2:
break;
case 3:
break;
default;
}

EXAMPLE
let num=3
switch(num){
case 1:[Link]('A');
break;

case 2:[Link]('B');
break;

case 3:[Link]('C')
break;

default:[Link]("Default");

LOOPS AND STRINGS


-----------------
1)for loop
2)while loop
3)do while loop
4)for each
5)for in
6)for of

while loop
Syntax
while(condition){
//Logic
updation
}

STRINGS
---------
sequence of character

lenth
//Length of an string
//let y="hello";
//[Link]([Link])

substring
let s="Hello";
[Link]([Link](2,4));//dont include ending character

concatination
toUpperCase
toLowerCase
//let y="hello";
// let s="HELLO"
// [Link]([Link]());
// [Link]([Link]())

split
let a="Hello \\ my \\ name \\ is \\ ganesh";
let b=[Link]("\\");
[Link](b);
[Link]([Link]());

FUNCTION
*code reusability
*provide flexibility
*we cant write anything after return statemnet because it will treat as unreachable

3 WAYS FOR DECLARING FUNCTIONS IN JavaScript


1)normal declaration
2)using expression
3)using ARROW function

Syntax
function function_name(parameters){
//statements;
}

EXAMPLE1
function sayMyName(){
[Link]("Love babbar");
}
sayMyName();//function call

EXAMPLE2

function sum(a, b){


let sum=a+b;
return sum;
}
let a=sum(5,5);
[Link](a);

ARROW FUNCTION
----------------
Synatax
let getName=(x)=>{
let g="hey";
return g;
}
getName();

ARRAYS
-------
collection of items.

Syntax
[]
array constructor

let arr=[1,2,3,4];
let arr=[1,2,3,4,5];
[Link](arr);
//array constructor
let brr=new Array("love",2,"mocktail",true)
[Link](brr);
[Link](brr[0])
let obj={name:"ganesh",
age:20};

METHODS IN ARRAY
------------------
push
pop
shift
unshift
slice
splice-----we can chage array content
map------------
let arr=[10,20,30,40];
let ans=[Link]((number) => {
return number*number;
})
[Link](ans);

filter
let arr=[1,2,'love','kunal',null];
let ans=[Link]((value)=>{
if(typeof(value)==='string'){
return true;
}
else{
return false;
}
});
[Link](ans);

reduce

let arr=[10,20,30,40];
let ans=[Link]((acc,curr)=>{
return acc+curr;
},0);

[Link](ans);

sort
Ascending order
let arr=[9,1,7,4,2,8];
[Link]();
[Link](arr);

//Descending order
let arr=[9,1,7,4,2,8];
[Link]((a,b)=> b-a);
[Link](arr);

indexOf
let arr=[10,20,30,40]
let ans=[Link](30);
[Link](ans)

find//Home work

FOR EACH
let arr=[1,2,3,4,5,6];
[Link]((value,index)=>{
[Link]("Number:",value,"index: ",index);
});

FOR IN

ARRAYS WITH FUNCTION


let arr=[10,20,30,40];

function getSum(arr){
let sum=0;
[Link]((value)=>{
sum=sum+value;
});
return sum;
}
let result=getSum(arr);
[Link](result)

object
-------
unorder collection of key value pairs.

//array constructor
let brr=new Array("love",2,"mocktail",true)
[Link](brr);
[Link](brr[0])

//shalov copy and deep copy

CALL STACK AND HOISTING


-----------------------
//Example1
Hoisting---process where it will shift variable declaration(var) and function
declaration to the top in their scop.
sayMyName("Babbar");
function sayMyName(finalName){
[Link](finalName);

}
//Example2
[Link](age);
var age=25;

FUNCTION CALL STACK


why we call functions as first class citizen?
because we can assign as variable
we can pass arguments
we can return function
we can use it in data structure

variable scoping
----------------
1)global scop//we can access it any where inside function loop anywhere
//global scop
/*var age=25;
[Link](age);
if(age>=18){
[Link]("can vote")
}
else {
[Link]("cant vote");
}
{
[Link](age);
}
for(let i=0;i<2;i++){
[Link](age)
}

function myAge(){
[Link](age);
}
myAge();*/

2)function scop//if we create variable inside function we cannot able it to access


outside the function
let greet=(()=>{
let my="how are you";
[Link]("hey",my);

});
greet();

3)block scop

let is a block scop

{
var age=100;
}
[Link](age);

TEMPORAL DEAD ZONE


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

CLASSES
--------
is blue print which has behavior and properties

class human{
//properties
age=20;
wt=50;
hg=180;

//behavior

walking(){
[Link]("walking");

}
eating(){
[Link]("eating");
}

}
let h=new human();
[Link]();
[Link]();
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);

**to make private we have to put #


#age=20;

DEFAULT parameters
functions with default values

built in objects
1)MATH OBJECT
1)[Link]
2)[Link]
3)[Link]
4)[Link]
5)[Link]//return smaller value if the value is 1.9 it will return 1
6)[Link]//it will return bigger value if it is 1.9 it will return 2

[Link]([Link](156,345,235,123,986));
[Link]([Link](156,345,235,123,986));
[Link]([Link](14.05));
[Link]([Link](15.99));
[Link]([Link](15.01));
[Link]([Link](25));

2)DATE OBJECT
let curr=new Date('September 17 2024 07:30');
[Link](curr);
let curr=new Date(2004,8,17,7);
[Link](curr);
[Link]([Link]())
[Link]([Link]())

OBJECT CLONING
--------------
objects are dynamic in nature because we can change repoerties of object in runtime

3 ways for Cloning


1)using spread operator(...)
let src={
age:20,
ht:180,
wt:50
}
let dest={...src};
[Link]=25;
[Link](src);
[Link](dest);

2)using assign
let src={
age:20,
ht:180,
wt:50
}
let src2={
value:20,
name:"Ganesh"
}
let dest=[Link]({},src,src2);
[Link]=190;
[Link](src);
[Link](dest);

3)using iteration

GARBAGE COLLECTOR

Error Handling
----------------
An event which occur during program execution

1)Compiled time Error


2)Run time Error

Handling:-
---------
try-catch block

JavaScript DOM(Document object model) Manipulations


-----------------------------
DOM means converting my html coed into javascript object;

(BOM--browser object model:-the interaction of browser except html content like


navigation ,screen size and so on)

accessing element
-----------------
1)by id
2)by class
3)by tag
4)by $0

Updating existing element


1)innerHTML--(get/set:getting and setting)
2)outerHTML--(home work)
3)text-content---
4)innerText

Adding Elements
---------------
1)creating child element using---createElement()
2).appendChild()---Adiing at end
3).prepend()--adding content in beging or first
4)insertAdjcentElement();----Insert element at any position
there are 4 position 1--before begin
2---afterbegin
3---beforeend
4---afterend

let mydiv= [Link]('#mydiv');


mydiv;
let newelement=[Link]('span');
[Link]="this is me love babbar";
[Link]="this is me love babbar";

Removing Elements
--------------------
removeChild()----opposite of appendChild and have to mention removing from which
parent
and removing content (child)
Example
let parent=[Link]('#mydiv');
let child=[Link]('#fpara');
[Link](child);

Changing CSS using JavaScript


-----------------------------
1).style--we can set it get it but only one inline style at a time
let paraElement=[Link]('fdiv');
[Link]='red';

2).[Link]--we can set and get multiple inline style

Adding classes and Id using


-----------------------------
1).setAtrribute()--it will set value for id and class

let firstElement=[Link]('#fdiv');
[Link]('class','divClass');
[Link]('style',"padding:0.1rem");

2).className;
let firstPara=[Link]('fpara');
[Link];
[Link]="abhi gani";

3).classList;
we can get,add,remove,toggle(toggle means if added then remove,in removed then
add),contains or not
let firstPara=[Link]('#fpara');
[Link];
[Link]("thirdclass");
[Link]("secondclass");
[Link]("firstclass");

Browser Events:-
----------------
1)Events---Events are announcement(if i clicked on window,button,key
press,scrollind it is an event)

i)Event-Target
-------------
it is an entity where ur event received
example : if there is a button and a boy click it ,so cliking is an event and the
button is event target and the action performed after clicking on it is event
listener

There are two form for event listener


1) addEvenetListener()---(it is always in bubling phase)
2)removeEventListener()

Synatax
-------
<event-target>.addEvenetListener(<event-type>,<function-->action>);

Example
--------
function changeText(){
let firstPara=[Link]('fpara');
[Link]="Hello ganesh";
[Link]="background-color:red; padding:2rem;"
[Link]("clicked")

}
let firstPara=[Link]('fpara');
[Link]('click',changeText);
[Link]('click',changeText);(for both adding and removing,
function should be same)

Phase of Event
---------------
1)Capturing Phase---from top to bottom(like div then article then para)
2)At-Target Phase---the last target or target element(for example is para)
3)Bubling Phase---returning back to top(para to div)

Event Object
------------
function changeText(event){
let firstPara=[Link]('fpara');
[Link]="Hello ganesh";
[Link]="background-color:yellow; padding:1rem;"
[Link](event)
}
let firstPara=[Link]('fpara');

Default action
--------------
let firstAnchor=[Link]('fanchor');

[Link]('click', function(event){
[Link]();
[Link]="click done bhai";
});

Avoiding to many Listeners(8:42:05)


--------------------------
function alertPara(){
alert("You have clicked on para :"+[Link]);
}
let myDiv=[Link]('wrapper');
[Link]('click',alertPara);

DOMContentLoaded()-----Home work

Performance Improvement
-----------------------

#standard wy to check performance of code


[Link]()----it will give one timestamp

Example

//Performance Improvement
//CODE 1
const t1 = [Link]();
for (let i = 0; i <= 100; i++) {
let para = [Link]('p');
[Link] = "this is para " + i;
[Link](para);
}
const t2 = [Link]();
[Link]("Total performance time of first code is: " + (t2 - t1));

//CODE 2

const t3= [Link]();


let mydiv=[Link]('div');
for(let i=0;i<=100;i++){
let para=[Link]('para');
[Link]="this is para 2 "+i;
[Link](para);
}
[Link](mydiv);
const t4 = [Link]();
[Link]("Total performance time of second code is: " + (t4 - t3));

REASON FOR FAST AND SLOW CODE


-----------------------------
1)reflow----it is a process of calculating position /dimension of element++

2)repaint----process of displayng content/element pixel by pixel

Document Fragment
-----------------
*light weight document object
*if we add something using this it will not add reflow and repaint

Evet loop
---------
1)synchronous code:-
2)Asynchronous code

to perform event loop we must know


1)call STACK
2)browser
3)callback queue

Need of Event Loop-----javascript is single threaded language ,along with that how
a Asynchronous
code will be handled,how concurrency will maintain,
how responsivness will maintain these all things will be handled by event loop

PROMISE
--------
It will handle returning value ,completion status of Asynchronous

3 Types of state's
------------------
1)Pending
2)fulfilled
3)rejected

if Promise are going to fulfilled we have to use then()


for failure and reject we have to use catch()

Asynch Await
------------
Using Asynch await we can show our Asynchronous code to Synchronus code
//await -
//Fetch API

You might also like