0% found this document useful (0 votes)
11 views117 pages

JavaScript

The document provides a comprehensive overview of JavaScript, covering its definition, history, execution methods, features, and how to integrate it with HTML. It discusses various JavaScript concepts including variables, data types, scopes, and input/output statements, along with practical examples. Additionally, it highlights the differences between variable declaration keywords such as var, let, and const, and explains the dynamic nature of JavaScript as a programming language.

Uploaded by

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

JavaScript

The document provides a comprehensive overview of JavaScript, covering its definition, history, execution methods, features, and how to integrate it with HTML. It discusses various JavaScript concepts including variables, data types, scopes, and input/output statements, along with practical examples. Additionally, it highlights the differences between variable declaration keywords such as var, let, and const, and explains the dynamic nature of JavaScript as a programming language.

Uploaded by

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

JavaScript

TOPICS: ---
1)What is JavaScript 24) diff b/w textcontent
and innerhtml
2)History 25) Timers
3)How JS runs internally 26) Events
4)Features 27) Math js
5)How to add JSHTML 28) Template literals
6)output & input statements in JS 29) Destructing of array
object
7)JS variables (Rules, keywords) 30) spread operator
8) JS scops 31) Rest parameter
9)Datatypes 32) closures
10)Operators in JS 33) Hosting
11)Functions (types, ways to create) 34) Currying
12)JS objects(ways) 35) synchronous & asynchronous
13)CRUD operations 36) Event loop
14)Nested objects (adding fun, array) 37) promise in js
15)Object methods 38) Fetch
16)JS Array 39) Callback
17)Array methods 40) This keyword
18)Advance Array methods 41) lexical scope
19)JS strings 42) try – catch - finaly
20)string methods
21)conditional stmts
22)loops
23) DOM methods
JavaScript

Scripting
programming lang

Front-end
Backend

To add functionality/behaviour process


the action
to html elements
web browser
node js

JavaScript: JavaScript is both scripting and programming lang.


used to add functionality/behaviour to html
element in a Front-end for scripting and also used to processing
the action in Backend
HISTORY: JS started year1995(by add/giving dynamic
nature/ pages)
Father-->Brenden Eich belongs to nets cape
organization (it is a browser in an olden days)
WHY?: JS introduced for adding dynamic nature to the static
page

1995->Brender Eich

JS

Initial name= “mocha”

after rename as= Live script

JavaScript
NOTE: live script is re-named into JavaScript just because of
marketing strategy. -->there is no relationship between java and
Jscript
1995mochalive scriptNetscapeBrenden Eich
1996MicrosoftNetscape (Jscript)internet Explorer
{compatibility issues}
1997JS was standardized by ECMA (European computer
manufacturers association) ES1 but we use ES6 (now ES25)

----HOW JavaScript RUNS OR EXECUTES


(18/11/25)
INTERNALLY
Python—PVM, java – JVM
2 ways we can execute:
V8 chrome browser (JavaScript engine) and node js(extra
environment)
Js execute through browser (Netscape)named as spider
Monkey
Js executed through front-end development browser
Js component has (charger)parser (check line by line) and
compilers (dump) heap memory (store all objects) & call stack
Js compilesbrowser (will take js code)code execution (JS
engine)validation & every declaration in is codethrows
error just-in-time compiler (convert code into bytecode)
dump that into heap memory call stack
Developer consoleopen platform to all the testing or
debugging purpose for user
DEFINATION: JavaScript can be or executed/ run through
browser in a front-end Development while giving functionality to
html element
JS can also run through [Link]
node JS is an extra environment for executing JS outside the
browser
browsers will be having JS engines within it (browsers) and js
engine will execute JS through browser
Different JS engines: v8 in chrome browser, chakra
(Microsoft), spider monkey (Firefox), JS core(safari)

(19/11/25)— JavaScript Features:


--
1)JS is scripting and programming lang
add functionality to html Ele in front-end (Browser)
processing the action in back-end ([Link])
2)js is a interpreted lang
js code compiled line by line through process in JS engine, the
converted into bytes code through JIT compiler
3)JS is a lightweight lang
because of its easy syntax and JS consumes less space in
memory
4)JS is dynamically typed lang
why? In JS while declaration of the variable no need to
specify/define datatype of the variable
Eg: name=” anu”
Age=23
Note: In every lang memory allocation will happen to
variables based on datatypes
Then how memory allocation happens for js variable
in compilation time compiler understand the datatype of
variable based on the value assigned to respected variable
5)JS is an object oriented lang
bcz perform as real world
6)platform independent lang
writes in one location and runs in
anywhere(platforms)eg:os,linux etc…
7)Basically, JS is single threaded lang
synchronous operation
but also supported to multithreading (Asynchronous operator)
-using callback, promise, async/await
8)JS is both client and server side lang

HOW TO ADD JAVASCRIPT TO HTML


Why? JS is front-end
To add a functionality to html element
IN 2 ways we can add JSHTML
1)Internal JS
2)External JS
1)Internal JS: --
JS is added within the html doc(html)either in head or body
section using <script> tag
Syntax: <head> (or)
<body>

<script> <script>

//JS //JS code


code
</script>
</script>
</body>
</head>

2)External JS: --
Instead of writing JS code within document, here we make a
separate file for js with .JS extension
[Link] [Link]

To establish the connection between .html & JS we use <script>


tag either in head or body with SRC attribute

Syntax: <head> <body> (or)


Ex: [Link]
<script src=” path or js <script src=” [Link]
file></script> [Link]”></script>

</head> </body>

<Doctype html>
<html>
<head>
<title>JavaScript
[Link](“hello)

<body>

<script src=” [Link]”>

</script>

</body>

(20/11/15) --- OUTPUT AND INPUT STATEMENTS IN


JS
OUTPUT STATEMENTS: --display something to users
1)[Link] ()
2)document. write ()
3)window. Alert ()/alert ()
4)DOM method
document. getElementById ()
 . [Link]
 . [Link]
1)[Link] (): --
This method is used to display something in a developer console
of that webpage.
We use console. Log for testing & debugging.
.html <body> o/p

<script>
[Link](“hi
”) Console

</script> HI

</body>
2)document-write (): --
This method is used to display/print something on the
webpage/document

-
<script> o/p
HI
Document. Write(“hi”)
</script>
3)Window. Alert ()/alert (): --
Used to display / print something in a popup window at top
canter on webpage.
String
always alert instructions will load first
ok
after click on OK then reset to the elements will load
4)Document. getElementById(): --
Used to access and manipulate html elements dynamically using
JS
we want to add content means:--
<h1 id =” heading”>Pentagon</h1> add pentagon space
<p id=” para”></p>  add hyd
<script>
Document. getElementById(“para”).text content=” hyd”
</script>
INPUT STATEMENTS: --
PROMPT (): ---Used as input statement in JS, used to take the
value from user
Write a JS prog to add 2 numbers
<script>
A=prompt (“enter value for a”)
A=10
B=20
C=a+ b
[Link](c)
</script>
prompt displays like a popup window at top canter of
webpage

Consist of:string which we given a parameter to prompt ()

Text field user to add the data


Buttoncancel: null will return to respected
variable
OK: the value will return to respected
variable
Note: prompt always takes input in string datatype
“10”--typecasting Value of a Value of b

A--prompt (“value of a”) 10 20


OK Ok
“20” Cancel Cancel
b--prompt (“value of b”)
c=a+b
[Link](c)o/p 1020(bcz it is in string format)

21/11/25---- JAVASCRIPT VARIABLES


Variables are the container to store data/value in memory
Why variables?
store data name=”
anu”
use the data
data/value
perform some operations with data variable
Rules for variables declaration & variable naming
1)Always variable naming must starts with letters, or
with $ or _(underscore)
Ex: name=” anu”
$name= “anu”
_name= “anu”
2)we can’t start variable naming with number or with any
other special char except $ &_
Ex: %name= “raj”
|name= “anu”
3)variables are case-sensitive
 Ex: var x, var X
4)we can have number / other special char after first
letter of variable name
N1ame
Name1
Name %
5)we can’t have spaces in variable name
 Personname= “anu”
Person name= “anu”
6)we can’t take any predefined keyword in JS as variable
name
Like: This, finally, try, catch
This= “anu”
7)Always variable in JS should declare through variables
keywords
Such as: var, let, const
 Let name= “anu”
Name = “anu”
 Var name= “anu”
 const name= “anu

**** VARIABLE KEYWORDS IN JS


--------Var
--------Let used to declare the variables
in JS A
-------const
1)var: --
Var is legacy (old name) keyword in JS to declare a
variable
var keyword having functional scope
var variable can be redeclared and also those variable
reinitialized

Function demo () { Function demo () {


Var a=10 {
[Link](a)--10 Var a=10
{ [Link](a)-10
[Link](a)-- }
10
[Link](a)-10
}
}
}
[Link](a)----error
[Link] (a)----error
Var a=10

[Link](a)---10

Var a=20-------redeclaration

[Link](a)---------20

A=30-------reinitialization

[Link](a)-------30

2)let: --
let introduced in ES6 version of JS
let having block scope
let variable can be reinitialize but can’t be redeclare

Function demo () {
Let a=10
{
[Link](a)
Let a=10;
A=20 ---------
[Link](a)--- reinitialization
10
[Link](a)
}
Let a=30--------redeclaration
[Link](a)---error
[Link](a)
}

[Link](a)

3)const: ---
introduced in ES6 version of JS
const also a block scop
const variable can’t be redeclared and also reinitialize

Function demo () {

{ Const a=10

Const pi=3.14 Const a=20

[Link](pi) D=30

[Link](pi)

[Link](pi)

VAR LET
CONST

legacy keyword ES6 version


ES6

functional scope block scope


block scope

(22/11/25) ----- JAVASCRIPT SCOPE


SCOPE: IN JS, scope determines where a variable is
accessible in our program.
scope tells where and how variable can be used in program
TYPES OF SCOPES: --
1)Global scope
2)functional scope
3)block scope
4)lexical scope
1)GLOBAL SCOPE: --
If a variable declared outside the function in JS, i.e. global
scoped variable
we can be accessed anywhere in program.
Outside function
Inside function
Inside the block of
function
[Link]: ------ var a=10; global scope(we can take
[Link],const)
Function demo () {
[Link](a)--inside function
{
[Link](a)-inside block
}
}
[Link](a) -outside function
2)Functional /local scope: --
If a variable declared inside the function, i.e having
local/functional scope
can be accessed only withing that function
Inside function
Inside function block
Outside the function
[Link]: ------------function demo() {
Var a=10
[Link](a)
{
[Link](a)
}
[Link](a)
3)Block scope: --
If a variable is declared inside the block of function, i.e. having
block scope
block scoped variable should declare with let/const
block scoped variable can be accessed only within that block
[Link]: -----------Function demo () {
{
Let a=10:
[Link](a)
}
[Link](a)
}
[Link](a)
4)lexical scope: ---
Occurs in a nested function in JS
An outer function variable can be accessed inside the inner
function but inner function variable can’t be accessed in outer
function
[Link]: --------function outer () {
Var a=10; -outer function variable
[Link](b) (here also we declare)
Return function inner () {
Var b=20--inner function variable
[Link](a)
[Link](b)
[Link](b) (here we declare)
}

DATATYEPS: -----
JS is a dynamically typed lang
In a time variable declaration, no need to specify the datatype
compiler will understand the datatype of variable based on
value assigned to variable
Type conversion
Name= “anu”-define type of the value
Age=22
Datatypes define the type of value variable is storing
2 categories in datatypes
1)Primitive datatype
2)non-primitive datatype
1)Primitive datatype: --
it is a basic datatype, stored in a stack memory
primitive datatypes store value directly in a memory
primitive datatype holds single value in its variable
pd is immutable
8 datatypes such as: ---Numbers
String
Boolean
Null
Undefined
Symbol
Bigint
2)Non-primitive datatype: --
it is a complex datatype, stored in a heap memory
non primitive datatype stores references/address in a
memory
non primitive datatypes hold multiple values in its variable
it is mutable
object type(only one type )
Such as: -- object
Array
Functions
Date ()
PRIMITIVE DATATYPE: -----
1)NUMBER TYPE: it is a datatype of integers, decimal and
comes under number type
int and float does not support in JS
Ex: let num1=27
[Link](num1)
var num2=49.0067
[Link](num2)
const num3=-12
[Link](num3)
run: right click, integer terminal, type node primitive(filename)
2)String type: A data is enclosed with “or “”is comes under
string
Ex: var name=” anu”
Let city=” Mumbai”
Const age=”22”
[Link](n)
3)Boolean type: any variable which contains value true or false
such type of data comes under Boolean type
Ex: var isplaced=true;
Let ismarried=false
4)Null: declaring a variable and storing null value is called null
datatype
Ex: Let name=null
[Link](name)
5)Undefined datatype: declaring a variable and not assigning
any value is called undefined dt
Ex: var city
[Link](city)
6)Big int datatype: Any value which is greater than 2 to the
power of 53-1 comes under Big int less than it comes under
number type
Big int(12344566788523445678990n)
7)Symbol datatype: Any data which can be created using
symbol ()
Constructor comes under symbol types
NON-PRIMITIVE DATATYPE: -----
Object type: any variable if we are assigning array or object
comes under object type
Ex: var person={
Name: ”anu”
Age:22
Place:”hyd”
}
Console .log(typeof object)-object type
Types of operator: --
In JS we have special operator called type of operator used to
find the datatypes of any variable
Syntax:typeof<variable name>
Ex: 1) var id=59
[Link] (typeof id)number type
2)let name=” anu”
[Link] (typeof name)string type
3) var iscompleted=true
[Link] (typeof is completed)bool type
4)var person= {}
[Link] (typeof person)object
5)let names= []
[Link] (typeof names)object

Operators in JS
JS operators are symbols that are used to perform operations on
operands
Ex: c= a+ b operand
operator
1)Arithmetic operators+, -, *, /, %, ++(incre), --(decre)
2)comparison operators==,===(identical),! =,!==(not
identical), >, >=, <, <=
3)Bitwise operators&(and) *, |(or)+, ^(Xor), ~(not), << (left
shift),>> (right shift),>>> (right shift 0)
4)Logical operators&&(and), ||(or), !(not)
5)Assignment operators=(assign), +=(add assign), -
=,*=, /=, %=
6)Special operators?:(conditional stmt return value based
like if else)
,(comma ope allow multiple exp to be evaluated as single stmt)
Delete (delete property from the object)
In (check if object has the property)
New(create instances), type of(checks type of object)
1)Arithmetic operator: --
Ex: -- let pos=4
Let neg=-4
[Link] (4—4)  //8
[Link] (4+-4) //0
[Link] (20/10) //2
[Link] (20%10)//0
Var a=10
[Link](a++)-10
[Link](a--)11
[Link] (1+”3”)13
[Link] (1-“3”)-2
[Link] (1+”1” +2+2+”3”) 11223, (1+1+”3”)23
2)Comparison operators: --compare 2 operands
== loose equality allows type conversion
=== strict equality
Comparison with null, undefined or empty can produce
unexpected results
strings compared with numbers are converted to numbers
always prefer “===” avoid comparison with null or undefined
Ex: -- [Link] (5=="5") //allow type conversion 5 is nbr and
nxt 5 is convert to nbr true
[Link] (true=="true")false
[Link] ("hello"=="1")false
[Link] (null>=0)true
[Link] (null === undefined) //here it not alllow type
conversionfalse
[Link] (5<=5)true
[Link] ([]==0)true
[Link] (13!==13)false
[Link](undefined>=0)false
[Link] ("2">1) //2 string it is converted to nbr so,2>1 true
[Link] ("02">1)true
[Link] (1>"2")false
3)Bitwise operator: --perform operations on operands.
bitwise operator work on 32-bit binary representation of
number
&, |, ^ perform each bit
mainly used in low level tasks like performance flag graphics,
permissions, or binary data handling
Ex: [Link] (5&1)1
[Link] (5|1)5
[Link] (5^1)4
[Link] (5<<1)10
[Link] (5>>1)2
[Link] (-5>>1)-3, (5>>>1)2
4)logical operator: --
Ex: [Link] (10==20 && 20==33)false
[Link] (true && true)true
[Link] (true || true)true
[Link] (false)true
[Link] (!10==20)true
5)Assignment operators: --
let num=5
[Link] (num++)//post increment: value is logged first then
incremented
[Link](num)5
// [Link](++num)6 //pre increment:value is incrementd first
then logged
// let a=12
[Link](a--)--12
[Link](a)
[Link](--a)----11
var num=10
num*=2
[Link](num)-20
num/=2
[Link](num)-10
num%=2
[Link](num)0
num+=2
[Link](num)2
num-=2
[Link](num)-0
6)Special operators: --
let name="anu"
[Link] ("my name is "+name) ----my name is anu
[Link] ("my name is “, name) -----my name is anu
[Link] (50+50) ----100
[Link] (50,50) -------50,50

28/11/25 ---- JS Functions


Functions are block of code which are destined to perform a
specific task
we can call JS function many times to reuse the code.
Advantages of function: --
 Reusability of code (write once use multiple times)
 Less coding
How to create a function in JS?
always function name should represent particular behaviour
function won’t get automatically invoked until and unless we
invoked it
Syntax: function function_name () {
// Set of statements
}
Function_name () //function call

Ex: --- function fun () {


[Link]("hello")
}
Fun () ----------hello
Types of functions: ---
1)Named function
2)Parametrized function
3Return function
4)Anonymous function
5)Callback functions
6)Higher order function
7)Arrow function
8)IIFE’s function
9)Async function
1)Named Function: --it is a function with normal way without
passing any arguments is called named function
Ex: ----- function add () {
let a=10
let b=20
var c=a + b or
[Link](a+b)
[Link](c)
}
Add () ----30
2)Parameterized function: -- We can send any information to
the function by passing inputs/parameters
Syntax: --- function function_name(parameters) {
//set of code
}
Function_name(arguments)
Ex: function add(a,b) {
let c=a+b
[Link](c)
}
Add (20,30)
Parameters: These are the variables without scope
statements which is used to create to store the data and we
utilize inside the function
Arguments: where it will accept always the data to store for
the parameters
Ex: function details (name, age, city) { parameters
[Link] ("name”, name)
[Link] ("age"+ age)
[Link] ("city"+ city)
}
details('anu',22,"hyd") arguments
details("anusha",23)
o/p ----------name anu, age 22, city hyd
name Anusha, age 23
3)Return Function: ---Function which can return the results
and it should catch by separate variable and we can see
output
parameters/arguments-input--function-output--return
stmsts
return should be last stmts inside the function after return
stmts if you write anything it will not execute
Syntax: function function_name () {
// set of stmts
Return
}
Ex: function add () {
let c=100+200
return c
}
[Link] (add ()) ----------300
4)Anonymous Function: ----function without name is called
anonymous fun
Syntax: -- function () {
//set of stmts
}
anonymous function is mainly used as callback function
Function expression:
Function expression is the process of assigning a anonymous
function to a variable and making a call
Ex: named anonymous function
let greet=function () {
[Link] ("i am anonymous")
}
greet () -----I am anonymous
Ex: parametrized function
let add=function (a, b) {
let c=a+ b
[Link](c)
}
Add (100,300) -----400
Add (20,40) ----60
Ex: return anonymous function
let fun=function () {
return "hello"
}
[Link] (fun ()) --hello
5)Callback Function: --
Any function which are you passing as arguments those
functions are called callback functions
Higher order function: any function which is taking another
function as a arguments that function called higher order
function
function are called higher order function only if it takes
minimum one function as a arguments
Ex: function print () {

[Link]("hello")

fun(function(a,b){

let z=a*b

[Link](z)20

})

function fun(callback) {

callback

higher order }

fun(print())
call back fun

fun(add(10,2))

arguments

Ex2: higher(callback) {
Callback ()
}
Higher (function () {
[Link](“hello”)
})
EX3: Parametrized function
Function fun1(callback) {
Callback (10,2)
}
Fun1(function (X, Y) {
Let z=x*y
[Link](z)

6)Arrow Function: ---


Arrow function are introduced es6 version function keyword is
not used to create arrow function arrow function are used
mainly as callback function
Syntax: ()=>{
//set of code
}
Ex: named/normal arrow function
Let greet= () => {
[Link](“arrow”)
}
greet ()-arrow
Ex: parametrized arrow function
Let sum= (a, b) => {
Let c=a+ b
[Link](c)
}
Sum (10,40) 50
Ex: Return arrow function
Let sum= () => {
Return “welcome”
}
[Link] (fun ())
Ex: parametrized function
Let res= (x, y) =>x*y
[Link] (res (10,2)
Ex: callback higher order function
Function higher(callback) {
Callback ()
}
Higher (() => {
[Link](“hello”)
}
7)Immediately invoked function: ---
IIFEs are functions that are defined and executed immediately.
Ex1:(function () {
[Link] (“hello world”)
})();
Ex2:(function (name, age) {
[Link] (‘I am ${name}, I am ${age} years old’)
}) (‘virat’,35);
8)Async function: ---
async functions introduced in es8 make it easier to work with
promises. They are declared with the ‘async’ keyword and use
the ‘await’ keyword to pause executed until promise is resolved.
Asynchronous function programming means multiple tasks can
be executes concurrently and the program doesn’t wait for a
task to finish before moving to the next one.
Ex:
Difference b/w asynchronous function and synchronous
function

Asynchronous fun
Synchronous fun

In asynchronous programming multiple In synchronous


programming the

Task can be executed concurrently program executed


occurs sequentially

Ex: code Ex:


code

[Link] (“stmt 1”)


[Link] (“stmt 1”)

setTimeout(()=>{ consol
[Link] (“stmt 2”)

(3/1211/25) …... JavaScript


Objects
JavaScript is an object based lang
An object is a combination of properties and behaviour
objects is refers to real world physical entity
objects is a concept which will help us to store multiple
information in one variable
JavaScript is template based not class based here we don’t
create class to get the object but we direct create objects.
object in JS class is collection of key value pairs all keys
inside JS
objects must be unique.
we can create object in 3 ways: ----
How to create object in JS: -----------
There are the 3 ways to create object in JS
1)By using object literals
2)by using instance of object
3)by using an object constructor
1)By using object literals
Syntax: var object_name = {key: value}
Let
Const
Ex: var person= {
Name:” anu”,
Age:35,
City:” hyd”,
Gender:” female
}
[Link] (person)
2)By using instance of object
Syntax: var object_name=new Object()
Let
Const
Ex: var car=new Object ()
[Link]=” bmw”
[Link]=2025
[Link]=” red”
[Link](car)
3)By using an object constructor
here we need to create function within arguments each
argument value can be assigned in the current object by
using this keyword
The this keyword refers to the current object.
Ex: function emp= {id, name, salary)
[Link]=id;
[Link]=name;
[Link]=salary;
}
A=new emp(11,”anu”,50000)
[Link]([Link]+” “+[Link]+” “+[Link]);
Crud Operation in
Object
[Link] or access the data
[Link] or write the data
[Link] the data
[Link] the data

1)------------How to access the data


Syntax: Object_name
[Link]([Link]);
[Link](product,price);
2)------------How to change the keyname or update
Ex:Object_name. key name to update=new value
Product_name=”apple”
[Link](product);
3)-----------How to insert or add or write new property
inside the object
Syntax: [Link]=newvalue or
Object[“keyname”] =newvalue
Ex: product. brands=” apple”
[Link](product)
4)How to delete property or remove property from the
object
Syntax: delete object_name. key name
Ex: var obj= {
Name:” anu”,
City:” hyd”
Gender:” female”
}
[Link](obj)
[Link]
[Link](obj) //delete is a spl key word in JS
1Q) I have a product and I want to store information of
that product like product name, price, category, rating,
stock
Var product={
Pname=” realme”
Price=30000,
Category:” electronic”
Rating:4.5,
Stock: true,
}
[Link](product)

How to create a nested object in js?

{
Ex:let user={
o/p name: 'anu',

age: 22,

isplaced: true,

address: {
city: 'hyd',

name:"anu",
age:22,
isplaced:true,
address:{
city:"hyd",
state:"telangana",
pincode:507160,
area:{
area1:"new road",
doorno:267,
}
}
}
[Link](user)
[Link]([Link])
[Link]([Link])
[Link]([Link])
[Link]="anusha"
[Link]=2672
[Link]([Link])
[Link]([Link])

How to add function inside a object?


Ex:var person={
name:"anu",
O/p [ 'music', 'dancing', 'travelling' ]
age:22,
gender:"female",
city:"hyd",
play:function () { //we can’t use arrow function inside the object,
keyword not support
[Link] ([Link],"is dancing")
},
age:22,
hobbies: ["music", "dancing", "travelling"]
}
[Link] (person. hobbies)

4/12/25 …… Object Methods


How to retrieve only keys from object?
Syntax: object. keys (object_name)
Ex: var person={
name:"anu",
age:22, [ 'name', 'age', 'gender', 'city', 'play', 'hobbies' ]

gender:"female",
city:"hyd",
play:function(){
[Link]([Link],"is dancing")
},
hobbies:["music","dancing","travelling"]
}
var keys=[Link](person)
[Link](keys)
How to retrieve only Values from object?
Syntax: object. Values (object_name)
Ex: var person={ [

name:"anu", 'anu',

22,
age:22,
'female',
gender:"female",
'hyd',
city:"hyd",
[Function: play],
play:function(){
[ 'music', 'dancing', 'travelling' ]
[Link]([Link],"is dancing") ]
},
hobbies:["music","dancing","travelling"]
}
var values=[Link](person)
[Link](values)

How to seal Object?


Syntax: [Link] (object_name)
[Link](obj) seals an object means
you cannot add or delete properties
you can still modify the values of existing properties existing properties
become non-configurable (cannot be deleted or reconfigure)
Ex: let person={
name:"anu",
anu
age:22, { name: 'anu', age: 23 }
}
[Link](person)
[Link]([Link]) //allowed
[Link]=23 // update allowed
[Link]="hyd" //not allowed
delete [Link] //not allowed
[Link](person)
//we can not delete bcz it is fix
//adding new propertiy not allowed

What is Object. assign() method?


object. assign (target, sources) copies the own enumerable
properties from one or more source object to a target
Ex: let person={
name:"anu",
age:22,
}
let details={ { name: 'anu', age: 22, city: 'hyd', gender: 'female' }

city:"hyd", { city: 'hyd', gender: 'female' }

gender:"female" { name: 'anu', age: 22, city: 'hyd', gender: 'female' }


{ city: 'hyd', gender: 'female' }
}
[Link](person)
[Link](person,details)
[Link](details)
[Link](person)
[Link](details)
[Link](person,details)

What is Object. entries ()?


Syntax: Object. entries(object_name)
object. entries () is a method in JS that returns an array of key-value
pairs from an object
each key-value pair is returned as a nested array [key. value]
Ex: let person={
name:"anu",
[ [ 'name', 'anu' ], [ 'age', 22 ], [ 'gender',
age:22, 'male' ] ]

gender:"male"
}
let disp=[Link](person)
[Link](disp)

What is Object. freeze ()?


Syntax: object. freeze(object_name)
object. freeze () is a method used to freeze an object
you cannot add new properties
not remove existing properties
not change the values of existing properties
not reassign or reconfigure any property
Ex: let person={
name:"anu", female

age:22, { name: 'anu', age: 22, gender: 'female' }

gender:"female"
}
[Link](person)
[Link]([Link]) //allowed2
[Link]="anusha" //changes not allowed
[Link]=5.11 //add not allowed
delete [Link] //delete not allowed
[Link](person)

05/12/25…. JavaScript Arrays


Arrays are a kind of data structure where we can store any
data and there is no restriction about the data we storing. those
data we are going to call as element
array is indexed collection of any type of data.
In js array we can add any type od datatype inside js
How to create Arrays in JavaScript?
There are two ways to create object in JS
1)Array Literal
2)array constructor
1)Array Literals: -----
Syntax: var or
let or Array_name=[ ]
const
Ex: let arr=[23,true,"anu",{name:"anu",age:20},'c',false]
[Link](arr)
o/p:--- [ 23, true, 'anu', { name: 'anu', age: 20 }, 'c', false ]
2)Array constructor: -----
Syntax: var or
let or Array_name=new Array()
const
Ex: let number=new Array(10,20,30,40,50)
[Link](number) --[ 10, 20, 30, 40, 50 ]
How can I access the data present in an array?
Ex: Var arr = [1,” anu”, true,’c’,11, {name:” anu”, id:18}, false]
[Link](arr[4])
[Link](arr[6])
How to get the size of an array?
Ex: let arr= [1,"anu", true,'c',11, {name:" anu", id:18}, false]
[Link] (arr. length) ----7
How to create a 2D array?
Var arr2d= [“anu”, [10,20,30], true, 8055]
[Link](arr2d)
[Link] (aee2d [1][2])20

Array Methods
1)push ()
2)pop ()
3)unshift ()
4)shift ()
5) indexOf ()
6)lastindexOf ()
7)join ()
8)includes ()
9) reverse ()
10)slice ()
11)splice ()
1)Push (): ----
When we need to push any data to an array we use push
method push () always append the data to the end of the array
Ex: let arr=[]
arr. Push (10)
arr. push("anu") o/p: -- [ 10, 'anu', true, 333 ]
arr. push(true)
arr. Push (333)
[Link](arr)
2)Pop (): ---------
When ever we need to remove elements from the array we
use pop ().
pop () removes the element which is present at the last
index of an array
Ex: let arr = ["anu",11, true,81.17]
[Link](arr)
arr. Pop () o/p: -- [ 'anu', 11, true, 81. 17]
[Link](arr) [‘anu’,11, true]
arr. Pop () [‘anu’]
arr. Pop ()
[Link](arr)
3)Unshift (): ---------
When we need to push the data to the beginning of the
array. We use the unshift var arr=[20,"anu",true,20.88]
Ex:// [Link](arr)
// [Link]("anu")
// [Link](arr)
// [Link](19)
// [Link](arr)
Op:------ [ 20, 'anu', true, 20.88 ]
// [ 'anu', 20, 'anu', true, 20.88 ]
// [ 19, 'anu', 20, 'anu', true, 20.88 ]
4)shift (): ---------
To remove an element from the beginning of an array. we
can use shift ()
Ex: var arr= [10,"anu", true,14.55,"chinnu","y"]
// [Link](arr)
// [Link]()
// [Link](arr)
// [Link]()
// [Link]()
// [Link](arr)
o/p:---- [ 10, 'anu', true, 14.55, 'chinnu', 'y' ]
// [ 'anu', true, 14.55, 'chinnu', 'y' ]
// [ 14.55, 'chinnu', 'y' ]
5)indexOf (): -----
this method is used to find the index value of particular
element if the ele is not available inside the array then the
indexOf() will return -1
Ex: var arr = [10,"anu", true,"chinnu",23.33,"y"]
// [Link](arr)
// [Link] (arr. indexOf(true))
// [Link] (arr. indexOf("da"))
o/p:-- [ 10, 'anu', true, 'chinnu', 23.33, 'y' ]
2
-1
6)lastindexOf(): ------
this method is used to find the last index value of particular
element
Ex: var arr=["anu",100,"chinnu",100,true,99,100]
// [Link]([Link](100))
// 6
7)join(): ------
whenever we need to join all the elements inside the array
join() should be used to join() will join all the elements of an
array and return it in the string format
Ex: let arr=[10,"anu",true,45.66,"chinnu","y"]
// [Link]([Link]())
[Link]([Link](''))
[Link] ([Link]('$'))
o/p:--10,anu,true,45.66,chinnu,y
// 10anutrue45.66chinnuy
// 10$anu$true$45.66$chinnu$y
8)includes (): -------
includes () checks weather the data passed to its present
inside the array or not. if its present then it returns true else
it returns false
Ex: var arr=[11,"anu",true,"chinnu",45.67]
// [Link]([Link]("chinnu"))
// [Link]([Link](12))
// true
// false
9)reverse (): -----------
in order to reverse an array we use reverse ()
Ex: var arr=[10,"anu",true,15.9,"chinnu","y"]
// [Link](arr)
// [Link]([Link]())
// [ 10, 'anu', true, 15.9, 'chinnu', 'y' ]
// [ 'y', 'chinnu', 15.9, true, 'anu', 10 ]
10)Slice (): -------------
whenever we need to extract particular elements from
array we can use slice() it will not alter the org array
Syntax: slice(startindex,endindex)
Ex: var arr=[11,"anu",true,"chinnu",34.5]
// [Link]([Link](3))
// [Link]([Link](2,4))
// [Link]([Link](1,4))
// [Link](arr) //it will not alter org array
// [ 'chinnu', 34.5 ]
// [ true, 'chinnu' ]
//[ 'anu', true, 'chinnu' ]
// [ 11, 'anu', true, 'chinnu', 34.5 ]
11)splice (): ----------------
extraction starts at the start index ectracts the length number
of elememts from the array in case splice() it also alters the org
array
Syntax: splice (start, length)
Ex: let num=[1,3,4,5,6]
// [Link]("orginal before splicing"+num)
// let splicedArr=[Link](1,3)
// [Link](splicedArr)
// [Link]("orginal array after splicing"+num)
// orginal before splicing1,3,4,5,6
// [ 5, 6 ]
// orginal array after splicing1,3,4

6/11/25: ------ Advance Array Methods


12)forEach (): ----
if we want to access each and every element of an array we
are using forEach()
forEach() will not return any value it will not alter org array
Syntax:<array-name>.forEach(function(ele,index){
[Link](ele,index)
})
Ex: var arr=["anu",11,"chinnu",true]
// [Link]((ele,index)=>{
// [Link](ele+" "+index)
// })
// anu 0
// 11 1
// chinnu 2
// true 3
13)map(): -------
map() should be return some value returned value always
added in new array map() will not alter org array
Ex: var arr1=[10,12,13,14,15]
// var arr=[Link]((ele,index)=>{
// return ele*10
// })
// [Link](arr1)
// [Link](arr)
// [ 10, 12, 13, 14, 15 ]
//[ 100, 120, 130, 140, 150 ]
14)filter (): ---------
it is used to filter ele or data from the array based on
certain condition
filter callback function will return always Boolean value it
will not alter org array it will create new array
Syntax: <array-name>.filter(function(ele,index){
Return <Boolean value>
})
Ex: let num=[11,120,230,414,66]//find the ele which is greater
than 200
// let arr=[Link]((ele)=>{
// //return ele>200
// return ele<200
// })
// [Link](arr)
// [Link](num)
// [ 230, 414 ]
//[ 11, 120, 66 ]
// [ 11, 120, 230, 414, 66 ]
15)reduce (): --------
it is used to reduce the array to one single value reduce
method is such a method which accepts a callback function as
the parameter(first param)(second param)initial value
Syntax: reduce(callback, initial-value)
Ex: let arr=[10,20,30,40,50]
// let callback=((prev,current)=>{
// //let res=[Link]((prev,current)=>{
// return prev+current
// })
// var res=[Link](callback,0)
// [Link](res)
16)sort (): ------------
is used to sort the array either in asc or des order
Ex: var names=["anu","chinnu","lucky","ajay"]
// [Link]([Link]())
// [ 'ajay', 'anu', 'chinnu', 'lucky' ]
Ex2: var arr=[10,30,20,69,35]
// //var result=[Link](function(a,b){ (or) -->nrml function mthd
// var result=[Link]((a,b)=>{ --->arrow mtd
// return a-b
// })
// [Link](result)
// [ 10, 20, 30, 35, 69 ]

17)tostring (): ---------------


the tostring() returns a string with array values separated
by commas and it does not charge the org array
Ex: tostring
// let bikes=["Ktm","royal","yamaha"]
// [Link]([Link]())
// Ktm,royal,yamaha
18)delete (): -----------
array ele can be deleted using js operator delete using
delete leaves undefined holes in the array
Syntax: delete array-name[index]
Ex: let fruits=["banana","grapes","pineapple"]
// delete fruits[2]
// [Link](fruits)
// [ 'banana', 'grapes', <1 empty item> ]
19)isArray () :-----------
the isArray() method returns true if an variable storing an
array otherwise
False
Syntax: [Link](variabelname)
Ex: let arr=["banana","apple","grapes"]
let content="welcome to home"
[Link]([Link](arr))
[Link]([Link](content))
true
false

JavaScript Strings
collection of characters enclosed with in
quotes(single/double) is considered to be string
Var str=”anu” // valid
Var str=anu //invalid
1)String concatenation: ----
combining one or more string together is called as
concatenation inorder to concat 2 strings we should take the
help of + operator
Ex: ar first="anu"
// var last="sha"
// [Link](first+""+last)
// Anusha
How to find the length of a given string?
to find the length of a given string we use length property
Ex:let city =”hyd”
[Link] (city. Length)-3

String Methods
1)charAt()
2)toLowerCase()
3)toUpperCase()
4)slice()
5)substring()
6)replace()
7)replaceAll()
8)trim()
9)concat()
1)chatAt(): -------
if we need to extract a specific character we use charAt()
Ex: var str=” hello”
[Link]([Link](4))
2) toLowerCase(): ------
to convert upper case to lower case
Ex: [Link] ([Link]())
3) toUpperCase(): ------
to convert lower to uppercase
4)slice (): -------
when ever we want to extract substring a string we can use
slice
Syntax: slice (start-index)
Slice (start-index, end -index)
5)substring (): ----------
it is almost similar to slice ()
the difference b/w substring and slice is substring does not
take -ve index
Ex: [Link] (str. Substring (2)) --valid
[Link] (str. Substring (-2)) ---invalid/not valid
6)replace (): --------
we want to replace a particular string with new string we use
replace
Ex: [Link] (str. Replace (“hello”,” hi”)
7)replaceAll():------
replace all are the occurrences with new string we can’t use
replace rather we should use replaceall
Ex: var str=”hello hello world”
[Link]([Link](“hello”,”hi”)) // hi world
8)trim (): ------
to remove the white spaces from the string
Syntax: str. Trim ()
Ex: var str=”hello world”
[Link](str+”welcome”) // hello world welcome
1)trimstart(): ---- To remove starting space
Ex: console. log([Link]()+”welcome”)//hello world welcome
2)trimend(): -----to remove ending space
[Link]([Link]()+”welcome”)// hello worldwelcome
9)concat(): -------
it is used to concat two string
Syn:[Link]([Link](str2))
Ex:let fname=”anu”
Let lname=”sha”
[Link]([Link](name)) //anusha

Selection statement or control stmts


we can control the execution of the program using control or
selection stmts. we can execute certain set of stmst only if
certain condition become true
CONDITIONAL
STATEMENTS
1)if stmt 2) if else stmt 3)else if stmt
4)switch stmt
If(condition) { if(condition){ if(condition)
{ switch (){
……. } }
case:”value”{
} else{ else if {
……
} }
break
else if {
}
}
case : “value”{

Break }

5)Switch stmt: 6)ternary


operator
Switch () { condition? //true stmt//
false stmt
Case:”value1”: ex: var fname =”anu”
{}
[Link](“sha”)?
Case:”val2”: [Link](“my
name is anu”):
{} [Link](“ur
name is something else”)
Default”{ o/p : my name is anu
}

Loops
Loops are used to complete repetitive tasks early instead of
manually repeating the task we must take advantage of loops
Types of loops:---
[Link] loop
Syn: for(initialize; condition; Incre/decr){
///stmts }
Ex: for (var i=0;i<10;i++) {
[Link](“the val is “+i)
}
o/p: 1 to 9
[Link] loop
Syn: while(condition) {
…………….}
Ex: var counter=0 o/p: 1 to 9
While(counter<10){
[Link] (“counter value is”+counter)
Counter++
}
[Link] while loop
Syn:do{
//exe the stmts }
While(condition)
Ex: let count=0
do{
[Link](“the count vaue is “+count)
count++
}
While(count<10)
4)For in loop: we can iterate through the object and we can get
the access of all keys of object properties mainly this loop will
access the key of the object
Syn: for(<variable declaration> in <object name>){ }
Ex: var person= {
name:”anu”
age:22
city:”hyd”
}
for(var x in person){
[Link](x) //name,age,city(only keys names)
}
5)for of loop: we can iterate through the array and we can
access of all the elements in an array
Syn:for(variable name of array name){ }
Ex:var arr=[10,34,25,67]
for(var num of arr) {
[Link](num) } o/p: ---10,34,25,67
Note: for loop will not working object
for in loop will working array but it access only index value not
the element
NAN operator
When does NAN occur?
When you perform mathematical operator that does not return a
valid number
Ex: let result-0/0 //NAN

10/12/25…. DOM (DOCUMENT OBJECT


MODEL)
DOM is the interface b/w JavaScript and browser
javascript in order to communicate with the browser takes help
of dom.
dom is an tree like structure
document

----------------------------------------------------------------------
Head
body
-------------------------------------------------- div
Style script title link
---------------------------

H2 p

Main uses of Dom: -----------


1)allow us to make js interact with browser
2)we can write js to create, modify and delete html elements
3)we can add dynamical styles, classes and attributes to the
html element
4)Dom is very complex api (application programming
interface) which contains lots of methods and properties which
help us to interact with browser
Why Dom is created?
using JavaScript, we can manipulate the html document so
the we can create dynamic user interface

Dom manipulation
how to access Dom node (html element)
how to add new html element
how to remove existing html element
how to change content or attribute of html elements
to perform above operation browser is providing us predefined
objects and functions called Dom API

Dom Methods
1)document. Write ()
2)document. Head ()
3)document. body
4)[Link]
5)[Link]
6)document. getElemntbyId ()
7)document. getElementByClassName()
8)document. getElementByTagName()
9)document. getElementByName ()
10) document. querySelector ()
11) document. querySelectorAll ()
12)document. createElement()
13)remove()
14)getAttribute ()
15)setAttribute ()
1)document. Write (): ---------
it helps us write some text directly to the html document
Ex: document. Write (“hi hello”)
2)document. Head (): ------------
it help to acces entrie head section of the html element
Ex: var head = document. head
[Link](head)
3)document. Body: ------------
it helps to access entire body section of the html document
Ex: var body = document. body
[Link](body)
4)[Link]: ------------
it helps to access url address of the html document
Ex: var url=[Link]
[Link](url)
5)document. title: ----------
it helps to access the title of the webpage
Ex: var title = document. Title
[Link](title)
6) document. getElementById(): -------
it is used to find the elements on the webpage based on the id
[Link] will return single element which matches with id
value
Ex: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1 id="one">welcome to js cls</h1>
<p id="two">Lorem ipsum dolor sit amet consectetur
adipisicing elit. </p>
<h3 id="three">Welcome to pentagonspace</h3>
<p id="para"></p>
<script>
let h1ref=[Link]('one') //access the
content
[Link](h1ref)
let pref=[Link]('two')
[Link](pref)
let h3ref=document. getElementById('three')
[Link]="thank you for visting" //change the text
let pararef=document. getElementById('para')
[Link]="hello how r u" //add the contect
</script>
</body>
</html>
11/12/25…… Difference b/w textContent and
innerHTMl
innerHtml: --
if we have any html tags present while using inner html then
inner html property recognizes the html tags
textContent: ---
if we have any html tags present while using textContent will
not recognises and it will print html tags as it is
Ex: </body>
<h1>Welcome to js class</h1>
<p>Lorem ipsum dolor, sit amet consectetur adipisicing
elit.</p>
<h3 id="one"></h3>
<h3 id="two"></h3>
<script>
//difference b/w textcontent and ineerhtml
var h2ref=[Link]('one')
//innerHtml
[Link]="<i>hello</i>"
var
p1ref=[Link]('two')//textContent
[Link]="<i>good mrng</i>"
</script>
</body>
7)document. getElementByClassName(): -----
by using this method we can access html elements
Based on class name
it will return the output in array format
Ex: <body>
<h2>class selector</h2>
<p class="p1">Lorem ipsum dolor sit amet consectetur
adipisicing elit.</p>
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit.
</p>
<p class="p1">Lorem ipsum dolor sit amet consectetur
adipisicing elit. </p>
<script>
let pref=[Link]('p1')
[Link](pref)
for(var x of pref){
[Link]="red"
[Link]="monospace"
[Link]="xx-larger"
[Link]="cyan"
}
</script>
</body>
8)document. getElementByTagName(): ------
it is used to find the elements using the html tag name and it
will return the o/p in array format
Ex: <body>
<label>username</label><input type="text"
name="username">
<label>password</label><input type="text"
name="password">
<br><br>
<label>username</label><input type="text"
name="username">
<label>password</label><input type="text"
name="password">
<h1>pentagonspace</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing
elit.</p>
<script>
let label=[Link]('label')
[Link](label)
label[1].[Link]="red"

let input=[Link]('input')
[Link](label)
label[1].[Link]="orange"

let pref=[Link]('p')
[Link](pref)
pref[0].[Link]="cursive"
pref[0].[Link]="green"
pref[0].[Link]="x-large"
</script>
</body>
9) document. querySelector (): ----------
it returns the first element in the document , that matches the
specific selectors or group of selectors
if no matches are found then it will return null
Ex: <body>
<h2>pentagonspace</h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
</p>
<h1>hello</h1>
<h4 class="four">this is heading</h4>
<h4 class="four">this is h4</h4>
<p id="one">Lorem ipsum dolor sit amet consectetur
adipisicing elit.!</p>
<p id="one">Lorem ipsum dolor sit amet, consectetur
adipisicing elit.</p>
<script>
let h1ref=[Link]('h1')
[Link]="blue"
let h4ref=[Link]('.four')
[Link]="green"
let pref=[Link]('#one')
[Link]="5px groove brown"
</script>
10)[Link](): --------
it is used to find the elements on th webpage based on the
name [Link] retuns nodelist it is nothing but arrat of node or
html
Ex: <body>
<label>username</label><input type="text"
name="username">
<label>password</label><input type="text"
name="password">
<br><br>
<label>username</label><input type="text"
name="username">
<label>password</label><input type="text"
name="password">
<h1>pentagonspace</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
</p>
<script>
let username=[Link]('username')
[Link](username)
[Link](username[1])
username[1].[Link]="pink"
username[1].[Link]="5px solid red"
let password=[Link]('password')
[Link](password)
password[0].[Link]="yellow"
password[0].[Link]="5px dashed green"
</script>
</body>
11) document. querySelectorAll ():--------
it returns all the elements which matches the query as an
array
12)document. createElement(): -----------
by using this mthd we can create the html elemnets
dynamically
 in order add the dynamically created element inside the
document
 or webpage we have take the help of append() or
appendChild()
Ex: <body>
<p>Lorem ipsum dolor sit amet consectetur adipisicing
elit.</p>
<div id="one"></div>
<script>
let btn=[Link]('button')
[Link]="click here"
[Link]="blue"
[Link]="white"
[Link]="none"
let body=[Link]
[Link](btn)
let h1ref=[Link]('h1')
[Link]="welcome to class"
[Link](h1ref)
let h2ref=[Link]('h2')
[Link]="hii"
let pref=[Link]('p')
[Link]="hello welcome"
let divref=[Link]('one')
[Link](h2ref)
[Link](pref)
</script>
13)remove (): ---------
by suing this method, we can remove the html elemnets
dynamically for the document
Ex: let href=[Link]('two')
[Link]()
let para=[Link]('three')
para [0]. remove ()
btn. Remove ()
14)getAttribute (): ---------
Ex:
15)setAttribute (): ---the set attribute (name, value)
method is used to set a new attribute or change the attribute
value existing attribute an html element

22/11/25--- TIMERS
when ever we need to delay the execution or we need call
function again and again we use timers
2 types: -----
1)set time out ()accept 2 parameters
1)callback function
2)the time in milliseconds
Ex: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let sayHello=()=>{
alert("hello good morning")
}
setTimeout(sayHello,5000)
</script>
</body>
</html>

2)set interval ()accept 2 parameters


1)callback function
2)the time in milliseconds
Ex: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let sayHello=()=>{
alert("hello how are you")
}
setInterval(sayHello,3000)
</script>
</body>
</html>
What is the difference between settimerout() and
setinterval()
the main difference between the settimeout() and set interval()
settimeout will execute the callback() only once
whereas setinterval() keeps on triggering the callback()
reguraly
after the given interval of time (unless you stop it)

Events
 All action in javascript we call it as events
Types in console onclick
[Link] action :
 Event is nothing but some activity on the webpage
Event consists of two things event listener and event handler
[Link] Listener :
It is used to catch the event occurred on the element
Example:-
[Link],onload,onsubmit,onkeydown,onmouseover,on
mouseout
Onclick :-
Ex:- <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!--onclick-->
<button onclick="greet()">Click here</button>
<button onclick="Darkmode()">Dark mode</button>
<button onclick="Generatepara()">generate para</button>
<button onclick="lightmode()">Light mode</button>
<script>
function greet(){
alert("good afternoon")
}
function Darkmode(){
[Link]="black"
}
function Generatepara(){
let pref=[Link]('p')
[Link]="I am dynamically generated para"
[Link](pref)
}
function lightmode(){
[Link]="skyblue"
}
</script>
</body>
</html>
Onchange:-
 Onchange events get triggred changing of dropdown option
Ex:- <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Document</title>
</head>
<body>
<select onchange="onDropdownChange(event)">
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
<option value="four">Four</option>
<option value="five">five</option>
</select>
<label>Gender</label>
<input type="radio" name="gender" value="female"
onchange="changeGenderOption(event)"">Female
<input type="radio" name="gender" value="male"
onchange="changeGenderOption(event)">Male
<script>
function onDropdownChange(e){
alert("option has been changed "+[Link])
}
function changeGenderOption(e){
alert([Link]+" option changed")
}
</script>
</body>
</html>
Onkeydown :
This events get triggred when we type any on <thead>
keyboard
Ex:- <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text" onkeydown="onKeyPress(event)">
<script>
function onKeyPress(e){
[Link]("key pressed"+[Link])
}
</script>
</body>
</html>
Eventcapturing :
The capturing phase is the first phase of event propagation in
the DOM
Event capturing means the event is triggred
First of an outermost or parent element and then it goes to the
innermost or child element
To perform event capturing for the add evnt listener along with
the event type and the callback function
We have to pass athrid argument as true
Syntax :-
[Link](event,function,true);
Or
[Link](event,function,{capturing:true});
 Event capturing direction will be from parent to child
Ex:- <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="parent">
<button id="child">Button</button>
</div>
<script>

[Link]("parent").addEventListener("click",fu
nction(){
alert("parent div clicked");
},true)

[Link]("child").addEventListener("click",fu
nction(){
alert("child button clicked");
})
</script>
</body>
</html>
Eventbubbling :
Event bubbling is mechanism in javascript where an event
starts from the deepest target element means the event tiggred
first child element or clicked element and then moves upward to
its parent element
In event bubbing event directions will be from child or parent
Why does event bubbling happens ?
 Javascript uses event propagation makes event delegation
possible reduces number of evnt listener in the application
Improve the performance of the application
Ex:- <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Document</title>
<style>
#parent{
border:2px solid black;
padding:20px;
width:20px;
}
#child{
margin:5px;
padding:10px;
background-color: lightblue;
border: none;
cursor:pointer;
}
</style>
</head>
<body>
<div id="parent">
<button id="child">Button</button>
</div>
<script>

[Link]("parent").addEventListener("click",fu
nction(){
alert("prent div clicked");
});

[Link]("child").addEventListener("click",func
tion(){
[Link](); //to stop event bubbling
alert("child button clicked");
})
</script>
</body>
</html>
[Link] handler:
It is function or javascript call
<button onclick=”fn()”>click me</button>
Event is a predefined object in javascript where it contains
All the information related to click event

Math JS
Mathobject :
Math is an in-bulit object In javascrpt which can be used to
perform some specific math operation
Ex:- [Link]([Link])//print value of pi
[Link]([Link](49))//print the square root of numvber
[Link]([Link](9,2))//print the power of number
[Link]([Link](5.6))//round to naearest number
[Link]([Link](2,5))//floor it to nearest integer value
[Link]([Link](23987.87765))//it will print integer value

//add remove the decimal value


[Link]([Link](-76567))
[Link]([Link](1773))//print the numebr is negative or
positive
[Link]([Link]())//print the random number

//Generate Random Numbewrs between 1-6


let res=[Link]([Link]()*6+1)
[Link](res)
DateObject :
 When ever we need to know about the date we should use
date
 Object gives infoomation regarding
day,month,year,minutes,hours, seconds and time zone
//month 0jan 11dec
//week0Sunday 6Saturday
Ex:- <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
//Date Object
//when ever we need to know about the date we should
use date
//object gives information regarding
day,month,year,minutes,hours
//seconds, and Time Zone
//month-->0-->jan 11--->dec
//week--->0--->sunday 6--->saturday
let date=new Date()
[Link](date)

//Methods of the date object


//[Link]() method is used to get the current date
let currendate=[Link]()
[Link](currendate)

//[Link]() is used to get the current month


//note month
let hour=[Link]()

//[Link]() is used to get the current day


var day=[Link]()
[Link](day)

//[Link]() method is used to print current


year
var year=[Link]()
[Link](year)

//[Link]() method is used to print current hour


var hours=[Link]()
[Link](hours)

//[Link] method is used to print current


minutes
Var minute=[Link]()
[Link](minute)
//[Link] method is used to printcurrent second
Var second=[Link]()
[Link](second)
</script>
</body>
</html>
How to stop setInterval()
when we need to stop the setInterval() we should use
clearInterval()
every setinterval() will return one id we need that id inorder to
clear the interval
clearinterval() accepts a number as a parameter

Template literals
template literals provide an easy way to interpolate
variables and expressions into strings
templates literals use back-ticks (‘ ‘) rather than the quotes (“
“) to define string

Destructing of array or
object
it is a technique in js to unpack properties or elements from
object or array and assigning variables
Ex: object distracting
Old approach new approach
Let
person={ const{name,age,city,gende
r}=person
Name:”anu”, [Link](name)
Age:22 [Link](age)
}
Let name=[Link]
Let age=person. age
[Link](name)
[Link](age)
Array old approach
new approach
Let name=[‘raj’,’nani’,’virat’,’ram’] let[emp1,
emp2, ..rest] =names let[emp1,emp2,…
rest]=names
Let emp1=names[0]
[Link](emp1)//raj
Let emp2=names[1]
[Link](emp2)//nani
Let emp3=names[2]
[Link](rest)//[‘virat’,’ram’]
[Link](emp1)//raj
[Link](emp2)//nani
If we didn’t do unpact
Ex:let[ , , emp3, emp4, emp5 ]=names
[Link](emp4)//ram

23/12/25---- Spread operator


it is used to copy properties of one object into another object
and it is used to copy elements of one array into another array.
Syn: <object name>
Or
<Array name>
Ex: applying spread operator for object
let obj={
name:"ram",
age:35,
city:"bangalore"
}
let obj1={...obj,
gender:'male',
email:'rama12@[Link]'
}
[Link](obj1)
//using spread operator in the array
let num=[10,20,30,40]
let num1=[50,60,70,80]
let array=[...num,...num1]
[Link](array)
let num2=[...num,90,100,101]
[Link](num2)

Rest parameter
rest parameter allow a function to accept an indefinite nbr of
arguments as an array and also it can applied for array or object
to store elements properties
Syn: function myfun(…args){
[Link](args)
}
Ex: rest with other parameters
function greet(greeting,...names){
for(let name of names){
[Link](`${greeting}, ${name}`)
}
}
greet("hello",'sravs','karthik','abhi','rama')
//example: Rest parameter for array
const num=[1,2,3,4,5,6,7,8,9]
const[num1,num2,...rest]=num
[Link](num1)
[Link](num2)
[Link](rest)
Clousers in JS
it is a technique to access of outer function variable inside
inner function
Or it is function to define function inside another function
A clouser can be defined as a js feature in which the inner
function has access to the outer function variable ,js, every time
a closuer is created with the creation of function
The clouser has three scope claims listed as follows
[Link] to its owm scope
[Link] to the variable of the outer function
[Link] to the global variable
Syn: function [Link]() {
Function function_name() {
}
Return function name
}
Ex: //Access the variable of its own scope
function outer(){
[Link]("i am outer function")
function inner(){
[Link]("i am inner function")
let city="bangalore"
[Link](city)
}
return inner
}
let res=outer()
res()
//Access the variable of outer function inside inner
function
function fun1(){
[Link](" i am outer function")
var name="virat"
return function fun2(){
[Link](" i am inner function")
[Link](name)
}
}
let result=fun1()
result()
//Access global function
var age=30
function person(){
[Link](" i am outer function")
return function fun2(){
[Link](" i am inner function")
[Link](age)
}
}
let details=person()
details()

24/12/25---- Hosting
hoisting is js default behaviour of moving variable and
function declarations to the top of their scope before
execution
How it will work
works with var (hoisted but undefined) and function
declaration (hosting with definition)
let and const are hoisted but remains in the temporal dead
zone (TDZ)
Both variables and functions are hoisted but different behave
How it works internally?
When js engine starts
[Link] phase (memory creation phase)
it scans the code
it creates memory space for variables and function
variable declarations are set to undefined
function declaration is fully hoisted (entire function
declaration)
[Link] phase
code runs line by line
Hoisting for var
Ex: [Link](a) //undefined
Var a=10
[Link](a) //10
Ex: var b // hoisting
[Link](b) //undefined
b=100
[Link](b) //100
Hoisting for let and const
Ex: Let b=20
[Link](b) //20
[Link](c) //reference error
Let c=200
let and const are also hoisted but kept in (TDZ) temporal dead
zone a period where the variable exisits bit is not accessible until
its initialized
Ex: let d; //hoisted
Hoisting for function
Ex: greet () //gm
Function greet () {
[Link] (“gm”)
}
entire function greet is hoisted so you can call it before
declaration
Note: only function declaration are fully hoisted function
expression and arrow functions are behaved like variables
Ex: say Hello () //type error
Var say Hello= () => {
[Link](“hello”)
}
say Hello() // hello

currying in JS
currying is a functional programming technique where a
function with multiple arguments is transformed into a sequence
of functions, each taking a single argument at time.
Or
currying breaks down a function that takes multiple arguments
into a series of functions that each take a single argument.
Example of a normal function
Ex: Function add(a,b,c) {
Return a+b+c;
}
[Link] (add (2,3,4)); //output:9
Example of a curried function
Ex: Function add(a) {
Return function (b) {
Return function (c) {
Return a + b+ c
}
}
}
[Link] (add (10)(20)(30)) //60
Benefits of currying:
[Link]: you can create specialized functions by fixing
some arguments.
Ex: const multiply=a=>b=>a*b
Const double=multiply (2)
Const triple=multiply (3)
[Link] (double (5))//10
[Link] (triple (5))//15
[Link] Application: you can create new functions by pre-
filling
Ex: const greet = greeting => name => `${greeting}, $
{name} !`;
Const sayHello =greet(“hello”);
[Link](sayHello(“alice”)); //” hello, Alice!”
Ex: const discount = rate => price => price – (price * rate);
Const tenpercentDiscount=discount (0.10);
[Link] (tenpercentDiscount (100)); //90
[Link] (tenpercentDiscount(200)); //180
[Link] Readability: functions can be more readable and
easier to understand.
Currying v/s normal function
Normal function
all arguments are passed at once
less reusability
Harder partial use
Currying function
arguments are passed one at a time
more reusability
easier partial use

26/12/25----- Synchronous function


A synchronous function is one that runs in a single thread
and completes its execution before moving on to the next
task.
it will block other operations until the current task is
completed.
synchronous programming means code execute line by line,
that is one task at a time and each line.
waits for the previous line to complete before executing.
Note: only one operation happens at a time
no parallel execution allowed
if any task takes time to complete, it will block the entire
program until that task is finished.
Example of synchronous code
Ex: [Link]("start")
function demo () {
[Link] ("demo function is running")
}
Demo ();
[Link]("end")
Asynchronous programming in
JavaScript

Asynchronous programming in JavaScript is a non-blocking


execution model
where long-running tasks can be executed in the background,
without while other operation can continue to run
Asynchronous programming is used with long-running tasks
like network request, file operation, timers, etc....
Note: In JavaScript Asynchronous programming execution take
care by the event loop
Event loop is part of the js runtime environment it is not part
of js engine
In js setTimeout and setInterval are the built-in functions
that allow us to perform asynchronous operations.
but we can also use promise. async/await for better handling
os async code
Example of Asynchronous code
Ex: [Link]("start")
function demo(){
setTimeout(function(){
[Link]("demo function is running")
},2000);//2 second delay
}
demo();
[Link]("end")
Event Queue
it is a data structure that stores all the request from the client
and waits for event loop to access event loop follows FIFO
principle
Event loop :
It is a mechanism in js that allows it to handle asynchronous
operations (like SetTimeout, Api calls, promises) without blocking
the main thread even though JavaScript is single thread

Why we need event loop?


js is single threaded language but some time it needs to
perform a long running task like fetching data from sever or
reading a file system
if js would have performed these tasks on main thread it would
have blocked the execution of other code so these tasks are
taken care by event loop
Note: event loop is not part of js engine it is part of browser or
[Link] runtime environment
Flow of event loop
So, if a js task is a synchronous that uses only js engine and
callback for execution
so, in js heavy tasks or asynchronous tasks go to web Api
through event loop
Event loop checks if a call stack is empty or not
If call stack is empty event loop pushes the microtask first to
call stack for execution then runs microtask next
If call stack is not empty event loop waits till it is empty
this process continue till all the tasks are executed
Event loop
Event loop is a mechanism in js that takes form web api or
tasks queue and pushes them to call stack when it is empty
why we need event loop?
js is single thread language but some time needs to perform a
long running task life fetching data from server or reading a file
system is js would have perform these tasks on main thread it
would have blocked the execution of other code so these task
care by event loop
Note: event loop is not part of js engine it is part of browser or
[Link] runtime environment
flow of event loop
[Link] if a js task is a synchronous that uses only js engine and
callback for execution
[Link] in js heavy tasks or asynchronous tasks go to web api
through event loop
[Link] loop checks if a call stack is empty or not
[Link] call stack is empty event loop pushes the microtask first to
call stack for execution them runs macro task next
[Link] call stack is not empty event loop waits it is empty
[Link] process continues till all the tasks are executed
microtask queue
microtask queue having higher priority in web api
api hold the async task made by promises, callback, async,
await and it always run before macrotask queue
macrotask queue
macrotask queue having lower priority in web api it hold the
async task made by setTimeout ,setInterval ,I/o operations and
dom evnts it excute after microtask queue is empty
What is web api
web appi is a browser or [Link] provided api that helps js to
perform
asynchronous tasks like setTimeout. fecth api, dom evnts etc....
web api is not part js engine it os of browaer or [Link]
runtime enviornment
sychronous--->browser-->js engine--->call stack -->excution
asychronus--->browser--->web api-->event loop-->task
queue -->call stack -->execution
29/12/25---- Promise in js
these are the way to handle the asynchronous operations

Def:A promise is a js object that links producing code and


consuming code
That represent a value may be available now or in the future or
never
Having 3 things
[Link]
[Link]
[Link]
Promises
----------------------------------------------------------------------------
| |
|
Fulfilled pending
rejected

Resolve ()
reject ()

then()
catch()
Creating a promise
creating a promise using promise constructor take a function
with two parameter resolve and reject
here the promise will be either be resolved or oi will be
rejected
Ex: let promdemo=new Promise((resolve,reject)=>{
let condition=true
if(condition){
resolve("promise fullfilled")
}
else{
reject("promise rejected")
}
})//fetch() ---used to fetch the data and call api’s
Handling promise result
To handle the promises we use 2 methods
1)fulfilled---then () method to handle the promise result
2)rejected-catch () if any errors occurs, then we use .catch
Ex:promise chaining
[Link](res)=>{
[Link](result)
})
.catch((error)=>{
[Link](error)
})
Promise—the better way
Creating a promise
const mypromise=new Promise((resolve,reject) =>{
const success=true;
if(success){
resolve("operation successful");
} else{
reject("opeation failed!");
}
});
//using a promise
[Link](result=>{
[Link](result);
})
.catch(error=>{
[Link](error)
});

Fetch
fetch is a method which works internally as a promise
fetch method is used to make a n/w request or to call a api in
js
Fetch will return a promise in js
Ex: fetch('[Link] //make api call
.then((res)=>[Link]()) //return promise fullfill
.then((jsondata)=>{
[Link](jsondata)
})//fullfill
.catch((error)=>{
[Link](error+"promise failed")
})//rejected

Modern way to call api by using Async and await


Async: declare a function or method as asynchronous and can
pause its execution to wait for completion of other process
Await: make a suspension point where execution may wait for
the result of async function or methods
Ex: async function fun1(){
//fetch the data from the url
let response=await
fetch('[Link]
//convert the response to json
let jsondata=await [Link]();
//log the json data
[Link](jsondata);
//you can also assign jsondata to a variable if you want to
use it later
let result=jsondata;
//log the results
[Link](result);
}
//call the async function
fun1();

Callback hell
callback hell happens in js when you have multiple nested
callbacks inside asynchronous function like settimeout, api calls
etc
it makes code harder to read and hard to maintain
it old pattern to handle asynchronous function in new pattern
we are using promises async/await method
Ex: [Link]("customer enters restaurent")
setTimeout(()=>{
[Link]("waiter takes order")
setTimeout(()=>{
[Link]("chief starts cooking")
setTimeout(()=>{
[Link]("food is ready")
setTimeout(()=>{
[Link]("waiter serves food")
setTimeout(()=>{
[Link]("customer starts eating")
setTimeout(()=>{
[Link]("customer pays the bill")
},1000)
},1000)
},1000)
},1000)
},1000)
},1000)

//example using promise

function step(message,time){
return new Promise((resolve)=>{
setTimeout(()=>{
[Link](message)
resolve()
},time)
})
}
//example using promises
function step(message,time){
return new Promise(resolve)=>{
setTimeout(() => {
[Link](message)
resolve()
}, time);
}
}
step("customer enters resturant",1000)
.then(()=>step("waiter takes order",1000))
.then(()=>step("chief starts cooking",1000))
.then(()=>step("food is ready",1000))
.then(()=>step("waiter servers food",1000))
.then(()=>step("customer starts eating",1000))
.then(()=>step("customer pays the bill",1000))
.catch(error)=>console. error("error",error)

30/12/25 ----This keyword


In js this is a special keyword which refers to current
object
Ex: let person={
Fname:”anu”,
Lname:”sha”,
Age:22,
Place:”hyd”,
Detail:function(){
[Link](“name is” +fname+””+lname+”age
is”+age+”from”+”[Link])
}
}
[Link]()
above code will result in error to resolve the error we need to
use this keyword
this keyword, this is a spl keyword in js which will point to
current object
we can change reference of this keyword by using three
predefined functions
1, call ()
2, apply ()
3, bind ()

1)call (): -----


for this function first arguments should be always object
for which this is refered
second argument is functions accepting arguments
Ex:var obj1={
C:100
}
Var obj2={
C:200
}
Function add(a,b){
[Link](a+b+this.c)
}
[Link](obj1,100,200) //400
[Link](obj2,300,200) //700
2)apply (): ------
the apply function it will take 2 arguments first argument is
object second argument is array
we can give function arguments inside the array
Ex: var obj1={
C:100
}
Var obj2={
C:500
}
Function add(x,y){
[Link](x+y+this.c)
}
[Link](obj1,[10,20])
[Link](obj2,[30,20])
3)bind (): ----------
the bind function will return same function by change
reference of this keyword
syntax: var fnName=<fnName>.bind(object_name)
where as call() and apply() will not return any function
Ex: var obj1={
C:100
}
Var obj2={
C:200
}
Function add (a, b) {
Let res= a+ b+ this. c
[Link](res)
}
let fun=add. bind (obj1) ------mtd 1
fn(100,200) //400
[Link](obj2)(200,300) -------- mtd 2
let fun2=add. bind(obj1,100,200) --------mtd 3
fun2() //400
add. Bind (obj2,100,200) () //900 --------- mtd4

Scope in js
Scope refers to the accessibility
scope can be used for functions and variables
There are 2 scopes in js
1, global scope
2, function scope

1)global scope:
if any function or variables or class or not defined inside
the block ({}) then they are said to be in global scope
Ex: var city=” Mysore” //global scope
Function fun1() {
[Link](city)
}
Function fun2() {
[Link](city)
}
Function fun3() {
[Link](city)
}
Fun1()
Fun2()
Fun3()
2)function scope: ----
anything which is defined inside the function scope those
things we can access only inside the function scope
Ex: function f1() {
Var name= ” anu”
Function fn () {
[Link](name)
[Link] (“fn is called”)
}
[Link](name)
Return fn
}
[Link](name) //error
F1()
Fn() //error

Lexical scope
lexical scope means that scope is determined by where
variables and blocks are written in the code means inner
scopes can access variables from their outer scope
Ex: function outer () {
Let a=10
Function inner () {
[Link](a) //can access a bcz of lexical scope
}
Inner()
}
Outer()

Try---catch---finally
whenever we feel some part of code may cause problems,
we must enclose the part of code with in the try.
so if any problems occur try is designed in such a way that
is throws the exception object outside which later will be caught
by the catch()
by using try-catch syntax we can avoid our programs getting
terminated abruptly
Syntax: try {
//code
}
catch(err) {
//to catch the error expression
}
Finally: ---------
finally block will get executed irrespective of exceptions
Ex: try {
Var num=20;
Fname:”anu”
[Link](‘num’+num) or (‘num’ / num)
[Link](err)
}
Finally {
[Link] (“finally executed”)
}
//manually throwing errors
Ex: try {
Var num=20;
Fname: (”anu”)
Throw new error (“product id not found”)
}
Catch(err) {
[Link](err)
}
Finally {
[Link] (“finally executed”)
}

You might also like