0% found this document useful (0 votes)
8 views50 pages

JavaScript

The document provides a comprehensive overview of JavaScript, detailing its introduction, differences from Java, and its execution environment. It covers key concepts such as data types, variables, type coercion, and the use of alerts, as well as the characteristics of let and const. Additionally, it explains the principles of programming languages and the structure of JavaScript code execution.

Uploaded by

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

JavaScript

The document provides a comprehensive overview of JavaScript, detailing its introduction, differences from Java, and its execution environment. It covers key concepts such as data types, variables, type coercion, and the use of alerts, as well as the characteristics of let and const. Additionally, it explains the principles of programming languages and the structure of JavaScript code execution.

Uploaded by

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

JAVA SCRIPT

04-09-2023

Introduction
 Introduced by Brendan Eich in 1995.
 It became an ECMA standard in 1997
 ECMA – European computer manufacture association 1997
 JavaScript and java are completely different language, both concept and design
 JavaScript is the world’s most popular programming language which is used on
browser to make webpages dynamic
 Netspace : It is a browser

Difference between Java and JavaScript

Java JavaScript
Programming Language Scripting language (It works on frontend)
(It works on middleware)
Strictly typed Weakly types
Eg: Eg;

Int n = 5; Var num =5;


Int x = 2 Var name =”tamil”;
String name = “Java”; Var n=15.23;
Runs on Java virtual memory Runs on all browsers
More memory used Less memory used
Independent language Executed along with HTML

How JavaScript works?

AST – Abstract syntax Tree


05-09-2023

Browser Name JS engine


Chrome V8 Engine
Mozilla Firefox Spider Monkey
Edge Chakra
Safari JavaScript Core

Environment of JavaScript
NODE JS
 Node is combination of a bundle of chrome V8 engine and built in methods in C++.
 It serves as an environment to run JavaScript outside the browser.
 This invention helped JS to gain its popularity in usage as a backend language.

Characteristic of JavaScript
Purely object orientated and object based. (Both primitive and non-primitive data types
are considered as object)
Interpreted language.
Case Sensitive.
Synchronous (It follows SINGLE thread architecture which has only one call stack)

Principles of programming language


Variable- Named block of memory.
Operator – It is a symbol has predefined function.
Block- Set of codes we should know how to call the function block.
Function – Code reusability

Ways to link JS code


INTERNAL
At the end of body tag

<script>

console.log("this is internal")
</script>
</body>
</html>
EXTERNAL
In html

<script src="../js/scriptSample.js"></script>
</body>
</html>

In CSS
console.log("this is external")

06-09-2023

Token
 Reserving something for someone.
 Smallest unit for every programming language.
There are 3 types
1. Keyword
2. Identifiers
3. Data Literals
Keywords

 Pre-defined words are called as keyword.


 Keywords are understandable by JS engine.
 There are 63 keywords
 All the keywords should be in lowercase.
 The words has some task to do.
Identifiers
Name given to component/attribute/member by the developer are called as identifiers.
1. Rule 1: Identifiers should be not start with number.
2. Rule 2: It should not have spaces between the words.
3. Rule 3: Only _and $ symbol are allowed to use. No other operators are allowed.
4. Rule 4: Camel Case
5. Rule 5: Pascal Case (Mainly used in Object, Class, and Constructors)
6. Rule 6: Special method snake case
7. Rule 7: Keyword should not be Identifier (or) Identifier should not be Keyword.

Data Literals
Data’s which you are using in JS program
1. String
2. Number
3. BigInt
4. Boolean
5. Null: we use null in absence of data.
6. Undefined: Given by the JS engine
7. Object
Primitive Non-primitive
String Object
Number
Boolean
Null
Undefined

Primitive data Non- primitive


Anything which cannot be developed Anything which can be developed
Inbuilt data type Developer creating data type

Fixed in memory size Do not consider memory size


Immutable Mutable
Stack Reference

typeof :
 It is keyword
 It is a special operator
 It is a unary operator
 It will tell what kind of data type

Data type
String:
Set of Character consider Sting in JS
We declare string in 3 ways

 Single quote (‘ ‘).


 Double quote (“ “).
 Template String (` ` - back ticks)
Advantages of Back ticks :
1. Expression are made in back ticks

Ex:
var ename=`smith's has iphone which has "apple13ver",he brought is for
Rs.${mobilerate}`
console.log(ename);

2.
Ex:

var stuName = "smith"


var stuLocation = "Banglore"
console.log( stuName +"\n"+stuLocation)
console.log( `${stuName} ${stuLocation}` )

Number:
Number are consider as number in java.
We don’t have any data type.
To access method or member use ‘.’ Dot
Ex:
console.log(Number.MAX_SAFE_INTEGER)
console.log(Number.MIN_SAFE_INTEGER)

Power: **
Multiplication: *

Range:
Max range:

console.log(Number.MAX_SAFE_INTEGER)
console.log(2**53-1).

Min range:

console.log(Number.MIN_SAFE_INTEGER)
console.log(-(2**53-1))

07-09-2023

Null
It is a keyword.
It has a value in JS
In the absence of data, we will be using null.

Undefined
var a;
It will create a memory block.

It is a keyword.
It has a value in JS
When a variable is declared in JS engine implicitly assign a value called undefined.

Boolean
From the user either you want to get yes or no.
In JS will be having Boolean data type (true/false).

Object
Any real entity which is existing in the real world.
JS object will be in the form of key & value (collection of named values).
Object in JS considered as non-primitive datatype.
Understanding the execution of Java script

SRC
Browser JS Engine Global Execution
Context

Variable check for Declaration:

var a; //Declaration
console.log(a)
Variable Functional
Phase /Execution Phase
1. It will allocate memory
2. Top to bottom

Execution Phase checks for instruction


1. Top to bottom

Output

Console (or)
Document

Every time when JS engine runs a JS code, it will 1st create a ‘global execution context’.

The global execution context has 2 phase:


a. Variable phase
b. Function/ execution phase

JS engine generally uses 2 phases to execute a JS code


a. Phase1: all the memory is allocated for the declarations in top to bottom order
and assigned with the default ‘undefined’ in variable area of global execution
context.
b. Phase2: all the instruction get executed in the top to bottom order execution
area of global execution context.
Variables
1. Named block of memory
2. To store data’s.
3. Dynamically typed.
3 Types
1. Var
2. Let
3. Const

Mandatory Not Mandatory


Declaring variable name is mandatory. Declaring data type

A named block of memory which is used to store a value is known as variables (Container
to store data).

Note:
1. In JS variables are not strictly typed, it is dynamically typed. Therefore, it not
necessary to specify type of date during variable declaration.
2. In a variable we can store any type of value.
3. It is mandatory to declare a variable name before using.

Syntax: var/let/const identifier;

Ex:
var a; //Declaration
a= 10; // Initialization or assigning
console.log(a); //10
let b ;
b=10;
console.log(b) //10
const c=30; //Declaration and initialization
console.log(c); //30

Note:
When a variable is declared in JS, JS engine implicitly assigns undefined value to it.
Ex:
var a ;
console.log(a) //undefined

Var (Playboy)
var a; //Declaration
a=10; //initialization
a=20; //Re-initialization
var a=30; //Re-Declaration and Re-initialization
var b=30; //Declaration and initialization
Const (serious guy)
const love = “marriage” // Declaration and initialization
cont love; //Declaration is not possible
love = “priya” // initialization is not possible
love = “akshaya” // Re - initialization is not possible
const love = “living together” //Re- Declaration and Re-initialization is not possible

08/09/2023

Browser Object Model

Inside window /browser we have predefined member, predefined member also consider as
an object.

Ex: console.log(window.console)

Example 1:
Variables Execution
console.log(“start”) a: undefined , 10 , 20 console.log(“start”)
var a; a=10
a=10 b: undefined , 20 console.log(a)
console.log(a) a=20;
a=20; console.log(a)
console.log(a) b=20;
var b=20; console.log(b)
console.log(b) console.log(“end)”
console.log(“end)”

Output:

start
10
20
20
End
Example 2:

console.log(“start”)
Variables Execution
var a=40;
console.log(a) a: undefined , 40, 50, console.log(“start”)
var a=50; 70 a=40
console.log(a) console.log(a)
var b=60; b: undefined , 60, 80 a=50;
console.log(b) console.log(a)
var b=80; b=60;
console.log(b) console.log(b)
a=70; b=80;
console.log(a) console.log(b)
console.log(“end”) a=70;
console.log(a)
Output: console.log(“end)”
start
40
50
60
80
70
end

Example 3:
Variables Execution
console.log(“start”)
a: undefined , 70, console.log(“start”)
var a;
smith console.log(a)
console.log(a)
a=70;
a=70;
b: undefined , true, 80 a=smith
a=smith;
console.log(a)
console.log(a)
b=true;
var b=true;
console.log(b)
console.log(b)
b=80;
b=80;
console.log(b)
console.log(b)
console.log(a)
console.log(a)
console.log(b)
console.log(b)
console.log(c)
console.log(c)
console.log(a)
console.log(“end”)

Output:

start
undefined
smith
true
80
smith
80
uncaught error ,c is not defined
11/09/2023

Type Coercion
Converting one data type to another data type
There are two types of type coercion
1. Implicit
2. Explicit

Implicit type coercion


The process of converting one data to another data type by JS engine. When wrong
datatype entered by developer.

var a = "5";//String
var b = 1;//number
var c = a+b;
console.log(c) //51
console.log(typeof c)//number converted into string.

console.log("ta"+"mil") //tamil
console.log("ta"+5) //ta5
console.log(12+12) //24

NAN - not a number


It is a keyword.
It is special number.
When you are trying to convert proper string into number.
Typeof NaN : number type.

var d = "5a" var a ;


var e = 5 a+=10
var f = d-e console.log(a) //Nan (undefined + number = NaN)
console.log(f) // Nan

var a = "5"
var b = 4
var c = a-b;
console.log(c)
console.log(typeof c) //1

isNaN() - method used to check number or not

console.log(isNaN("1a")) //true
console.log(isNaN("25")) //false

POP-UP
If we want to alert the user, we use pop-up.
There are 3types
1. Simple alert
2. Confirm alert
3. Prompt alert
Simple alert
Alert the user with information, there is no return type.
Ex:
var a1 = alert("Item has been added")
console.log(a1)

Confirm alert
Alert the user with information, there is Boolean (true/false) as return type.

Ex:
 HTML:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JS_task</title>
</head>
<body>
<script src="../js/confirm_alert.js"></script>

</body>
</html>

 JS:

var temp = true;

while(temp){
var a2 = confirm("please turn on your location");
if (a2){
window.location = "https://www.wikipedia.com";
temp = false;
}
else{
temp = true;
}
}

Prompt Alert
Alert the user with information, this return the input value given by the user.

Ex:
var a1 = prompt("enter your name: ")
console.log(a1) //Akshaya
console.log(typeof a1) //string

var a2 = Number(prompt("enter your age: "))


console.log(a2) //23
console.log(typeof a2) //number
Case 1:
For string:
var str = String(true)

console.log(str) //true
console.log(typeof str) //string

Case 2:

For number:
var num1 = Number("1a")
console.log(num1) //NaN

Case 3:

For Boolean:
1. var bool = Boolean(1)
console.log(bool) //true
console.log(typeof bool) //boolean

2. var bool = Boolean(undefined)


console.log(bool) //false
console.log(typeof bool) //boolean

False :
1. undefined
2. null
3. 0
4. “” (empty string)

12/09/2023

Characteristics of let and cons


1. Declaration
2. Scope
3. Hoisting
4. Temporal dead zone (TDZ)

Scope
Visibility of member

Block:
{
//Set of statements
}
Types of Block:
1. Named block
Controller have some restriction

while (n>10) {

}
2. Unnamed Block
Controller never have some restriction to go inside the block

TYPES OF SCOPE

Global Scope Local/Scrpit/Blog Lexical scoping


Var container Let/const Ability of JS engine
to search for a
Hoisting Visibility inside the
variable inside a
block
block
TDZ

Ex for scope:
var

var a = 10;
{
console.log(a)
}
console.log(a)

Ex for let and const:

var a = 10;

{
let b = 20;
const c = 40;

console.log(b)
console.log(c)
console.log(a)
}
console.log(b) //Uncaught ReferenceError: y is not defined
console.log(c) //Uncaught ReferenceError: y is not defined
console.log(a)
Variables Execution
a: undefined , a=10; Output:
10 { 10
b=20 20
b: undefined , C=40 40
20 console.log(b) 10
console.log(c) Uncaught ReferenceError: b is not defined
c: undefined , console.log(a)
40 }
console.log(b)

Ex by using window member:


var x = 10;
var y = 40;
var z = 50;

console.log(window.x)
console.log(window.y)

We can use same variable in different block level

var x = 10;
{
let x = 40;
console.log(x)
}
console.log(x)

Variables Execution Output:


window: a=10; 10
b=40; 40
a: undefined , c.l(window.a)
10 c.l(window.b)

b: undefined ,
40

---------------------------------------------------------------
let a =20;
{
var a = 10; Identifier 'a' has already been declared
}

Variable hoisting

1. Ex:
console.log(x)
var x;
x = 10;
console.log(x)
{
console.log(x) //cannot access 'x' before initialization
let x = 40
console.log(x)
}
console.log(x)

2. Ex:
var a =10;
{
let b=40;
{
console.log(a)
console.log(b)
}
console.log(b)
}
console.log(a)
console.log(b)
console.log(a)

Variables Execution
window: a=10; Output:
{ 10
a: undefined , 10 b=40; 40
{ { 40
b: undefined , 40 c.l(a) 10
{ c.l(b) Uncaught ReferenceError: b is
} not defined
} c.l(b)
}
} c.l(a)
c.l(b)

3. Ex:
var a = 10;
{
let b = 40;
{
let b =60;
{
console.log(b)
}
} Output:
b = 20; 60
console.log(b) 20

}
VAR LET CONST

Scope global local local

Hoisting   
TDZ (temporal dead zone)   

13-09-2023

Type Coercion
The process of converting one type of data into another data type.
Type conversion (implicit type casting)

IMPLICIT TYPE:
The process of converting one data type into another data type by JS engine implicitly
(implicitly type casting), when 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 into string
console.log(10-‘2’); //8, string is converted to number
console.log(5-‘a’); //NaN, the string does not have a valid numeric value
Hence it is converted to a special number ‘NaN’.

What is NaN ?
NaN(Not a number) is number
Any arithmetic operation with NaN, result is NaN.
Console,log(5-“1a”); //NaN

EXPLICIT TYPE:
The process of converting one type of value to another type of value by developers is
known as explicit typecasting.

Conversion of any number to number:


1. String to number:
If a string is valid number (‘5’), we get the real number.
If the string consist any other (“5a”), then we get NaN as output.

Ex:
console.log(typeof ‘a’); //string
console.log(number(‘a’)); //NaN
console.log(‘123’+10); //12310
console.log(Number(‘123’)+10); //133, string ‘123’ is converted to number
console.log(Number(‘123a’+10)); //NaN
POPUP’S

Simple alert - user can able to click ok (we can alert the user)
Confirm alert - - user can able to click ok and cancel (return type)
Prompt alert – user can able to give data’s
(Data’s getting from the prompt default it will be in string type)

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


statement. This characteristic is known as Hoisting.

DIFFERENCES BETWEEN var let and const:


var let const
Var is a global scope Let is block scope It is block scoped
We can declare multiple We cannot declare two We cannot declare two
variables with the same variables with the name variables with the name
name (mostly recently within a block. within a block.
created variable is used).
The value of variable can The value of variable can The value of variable
be modified be modified cannot be modified
Variables declared using var Variables declared using let Variables declared using let
is hoisted, does not belong is not hoisted, and does is not hoisted, and does
to temporal dead zone. Can belong to temporal dead belong to temporal dead
be used before zone. Cannot be used zone. Cannot be used
initialization. before initialization. before initialization.
Ex: Ex: Ex:
var a = 10; Console.log(a); //reference Console.log(a); //reference
a = 20; error (because of error (because of
console.log(a); //20 TEMPORAL DEAD ZONE) TEMPORAL DEAD ZONE)

let a = 10; const a =10;


a = 20; a = 20; //typeError
console.log(a); //20 console.log(a); //error,
assign the value only once

TEMPORAL DEAD ZONE:


The time between the variables which are created and its initialization is known as TDZ.

In TDZ period we cannot use variables.


let and const belong to TDZ.

Ex:
let a;
console.log(a); //Undefined
a = 10;

The problem occurs only if the variable used before declaration.

Ex:
console.log(a); //reference error(TDZ)
let a;
a = 10;
STRING:

We can create the string by 2 ways


1. By using string literals
Ex:
var str = “smith” //String literal

2. By using new operators


Ex:
var str = new String(“smith”) //new operator

Keyword Function/
Special Arguments
operator called as
values

Literals values are stored in stack area.


New object stored in reference area.

Ex:
var str = "Smith"
console.log(str)

console.log(str[0])

var str1 = str[0]="a"


console.log(str1)

console.log(str[0])

Stack Area

Identifier Address Values


str @001 Key Value
0 s
1 m
2 i
3 t
4 h

@str1001
str1 @002

str3 @003 Key Value


0 a

arr @001arr @arr003


Ex:
var str = new String("smith") // by using new operator
console.log(str)

var arr = [1,2,3]


console.log(arr)
console.log(arr[0]="A")
console.log(arr)
Reference Area

Address Values
@str1001 Key Value
0 s
1 m
2 i
3 t
4 h
Key Value
@arr003 0 A
1 2
2 3

14-09-2023

OPERATOR
Operators are pre-defined symbols whose work on operands

In JavaScript programming language, operators are classified into eight different


categories:

1. Arithmetic Operators
2. Assignment Operators
3. Comparison (Relational) Operators
4. Logical Operators
5. Bitwise Operators
6. Conditional Operators
7. String Operators
8. Special Operators

Arithmetic operators
var a = 10;
var b = 2;
console.log(a+b)
console.log(a-b)
console.log(a*b)
console.log(a/b) //Using division = Quotient
console.log(a%b) //Using modulus = Reminder

Post Increment and pre-increment


var a = 5;
var b = a++ + ++a; // 5 + 7
console.log(b) // 12

Assignment operator =, +=, -=, *=, /=, %=

var a = 10;

a+= 10;
console.log(a)

a = a+10
console.log(a)

a-=10
console.log(a)

a*=10
console.log(a)

a/=10
console.log(a)

a%=4
console.log(a)

Comparison operator or relation operator >, <, <=, >=, ==, ===, !=, !==

Equals ==
(Only values)

1. Primitive - non-Primitive
var num = 10;
var num1 = new Number(10)
console.log(num == num1)
------------------------------------------------------
2. Primitive - Primitive
// var str = "smith"
// var str1 = "smith"
// console.log(str == str1)
------------------------------------------------------

3. Non-Primitive - non-Primitive
var str =new String( "smith")
var str1 =new String( "smith")
// console.log(str == str1) // instead of using normal way use .member
console.log(str.valueOf() == str1)

Case 1:
var bool = true
var num = 1
console.log(bool == num) //true

Case 2:
var bool = true
var num = 5
console.log(bool == num) //false

Strictly equal ===


(data and values)

1. Primitive - Primitive
var str = "smith"
var str1 = "smith"
console.log(str === str1) //true
----------------------------------------------------
2. Primitive - Non-Primitive
var str = "smith"
var str1 =new String("smith")
console.log(str === str1) //false

// To overcome use .valueof()


console.log(str === str1.valueOf()) //true
-------------------------------------------------------
3. Non-Primitive - Non-Primitive
var str = new String("smith")
var str1 =new String("smith")
console.log(str === str1) //false

// To overcome use .valueof()


console.log(str.valueOf() === str1.valueOf()) //true
Strictly Not Equal !==
(Data and values)

1. Primitive - Primitive
var str = "smith"
var str1 = "smith"
console.log(str !== str1) //false

// To overcome use .valueof()


console.log(str === str1.valueOf()) //true
----------------------------------------------------
2. Primitive - Non-Primitive
var str = "smith"
var str1 =new String("smith")
console.log(str !== str1) //true

-------------------------------------------------------
3. Non-Primitive - Non-Primitive
var str = new String("smith")
var str1 =new String("smith")
console.log(str !== str1) //true

Logical operator AND OR NOT


&&
console.log(true && true) //true

||
console.log(true || false) //true

&&
console.log(!true && !true) //false
Conditional operator

var a = (true)? "this is true" : "this is false"


console.log(a)

Ex:

var age = Number(prompt("Enter your age :"))


console.log(age)

var age = (age>18)? "You can enjoy in PUB" : "Go to school"

alert(age)

Instance of:
var str = "smith"
var str1 = new String("smith")

console.log(str instanceof String)// false


console.log(str1 instanceof String)// true (we check instance of keyword only in string)

15/09/2023
Function

1. We treat function like first class citizens.


2. Treat function like available (like variables).
3. Function is a block of code designed to perform a particular task.
4. To achieve code reusability.
5. Function call is important.

Parameter: place holds some value/arguments/value.


Syntax:
function identifier (p1, p2){
function defination
//Block of statement
//function body
}
functioncall identifier (10, 20)
arguments

Parameter is consider as “local variable” of the function.

‘this’ keyword

It will point a variable.


This key point window object.
Two ways:
 All var variable belong to this keyword.
 Every function belong to var function.
CallStack:

1. A call stack is a way for the JavaScript engine to keep track of its place in code
that calls multiple functions
2. Stack of function to be executed
3. Manages execution contexts
4. Stack are LIFO last in first out

Example 1:
Variables Execution
console.log("start") this Console.log(a1+a2) //30
function sum(a1,a2){
console.log(a1+a2)
Variables Execution
}
window: console.log("start")
sum(10,20)
sum(10,20) 
console.log("end") this
console.log("end")
{
sum
}

Output
start
30
end

Example 2: Variables Execution


console.log("start")
this console.log(a)
function sum (){
console.log(b)
var a = 10;
var a: 10 console.log(a+b)
var b = 20;
console.log(a)
console.log(b) var b: 20
console.log(a+b)
} Variables Execution
sum() window: console.log("start")
console.log(sum) sum() 
console.log(a) // this
console.log(a)
console.log("end") {
sum console.log("end")
Output }

start
30
a is not defined
The JavaScript string is a sequence of character

There are 2 ways to create string in JavaScript


By string literal
By String object (using new keyword)
1. By String literal
The String is created using single, double, quotes and backticks.

var stringname = “string value”;

2. By string object (using new keyword)


The syntax of creating string object using new is given below:

var stringname = new string (“sting literal”);


here, new keyword is used to create instance of string.

STRINGS:
In JS String can be represented using single, double quotes or backticks.
Note:
The start and end of a string must be done with the help of same quote.
If a text contains single quote then it can be represented using double quotes.
Ex:
 Text: I’m a doctor
 IN JS: “I’ m a

Backticks:
A backticks can be multiline string.
Ex:
Var hobbies = `My hobbies are:
1. Cricket
2. Movies
3. Stock`;
console.log(hobbies);

Note:
The string represented using backticks is also known temple
The advantage of it is we can substitute and express it using $()
Example:
var str = “smith”
var str = new string (“smith”)
var str = new string (“smith”)

console.log( str == str1 ) //true


console.log( str === str1 ) //false

console.log( str1 instanceof string )

var str = “smith”


str = str.replace(“s” , ”j”)
console.log(str)
var str = “smith” // string literal
console.log(typeof str)
var str = new string (“smith”); //new keyword
console.log(typeof str1);
console.log(str1 instanceof String);

var student = “joys”;


var student1 = “smith”;
var student2 = “sam”;
console.log(typeof student);
console.log(student.concat(student1, student2));

console.log(student.lenght);
console.log(student.toUpperCase());
console.log(student.lowerCase())

console.log(student.repeat(5))

var str = “smith”;


console.log(student.slice(2,5))

var str = “smith”;


console.log(student.charAt(0))

var student = “smith”;


var student1 = “kenny”;
console.log(student.startWith(“sm”))
console.log((student.endsWith(“th”))

var a = “pune to banglore”


console.log(a.replace(“pune” , “chennai”));
console.log(a)

var student = “janith raj”;


var b = student.split(“”)
console.log(student.split(“”).reverse().join(“”))
console.log(student)

var student = “janith raj”;


console.log(student.trim))

19-09-2023

FUNCTION:

1. Named block of instruction used to perform specific task.


2. Function when executed only when it is called.
3. The main advantage of function, we can achieve code reusability.
4. MAIN PURPOSE: code reusability, which means code once declared can be used
anywhere.
5. In JS function are beautiful, every function is nothing but an object.
Syntax to create a function:
1. Using function declaration / statement (function statement)
2. Function expression.
3. Function declaration statement:
function identifier (parameter1, parameter2...)
{
statements
}
Note:
1. Function is an object.
2. Named of a function is a variable which holds the reference of function object.
3. Creating us can also call function before function declaration.

Ex:
console.log(‘start’);
test() //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 variables declared in the function definition/declaration is known as parameter.


The parameters have local scope. Those can be used inside the function body parameters
are used to hold the values passed by a calling a function.

Ex:
function sum(a,b)
{
console.log(a+b);
}
Here a and b are variables local to the function sum.
ARGUMENTS:

The values passed in the method call statement is known as arguments.


An argument can be a literal, variable or an expression which results a value

Ex 1:
sum(10,20)---------------------10, 20 are literals used as arguments

Ex 2:
sum(-10+3, -20); -----------//-27
Ex 3:
sum(a,b):------------------- a & b are variables used as arguments

this:

1. It is a key word used as variable.


2. It holds the address of global window object.
3. Therefore with the help of this variable, we can use members of global window
object.
Ex:
var b = 20
function test() {
var b = 30;
console.log(‘from test’ + b)---------------//30
console.log(this.b);-------------------------//20
}

FUNCTION EXPRESSION:

Syntax:

1. Var /let/const identifier = function(){}


2. In this syntax function is used as value.

Ex:
const area = function (width, height) {
return width * height;
};

console.log (area (3, 4));


// expected output: 12

Disadvantages:
The function is not hoisted, we cannot 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 function, it is undefined.

Lexical scope/ Scope Chaining


The ability of a function scope to access variables from the parent scope.
Ability of JS engine to sense for variable inside the block, if it is not present go for parent

Closure: Block of memory


Bind parent function variable to local function.
Nested Function
Variables Execution
console.log(“start”)
function outermost(){ window a = 10;
var a = 10; console.log(a)
console.log(a) a 10 console.log(innermost ())
return innermost ();
function innermost(){ innermost f
var b= 20;
console.log(b)
} Variables Execution
return inner most;
} window console.log(“Start”)
return outermost() console.log(outermost())
console.log(“end”) this console.log(“End”)

outer f x001
Output:
Start
outermost xcall01
10
20
End

TYPES OF FUNCTION:

1. Named Function:

A named function is a function that is defined with a specified name.

function add(a, b) {
return a + b;
}
console.log(add(5,4));//9

2. Anonymous Function:

An anonymous function in JavaScript is a function that is defined without a specified


name. Instead of providing a name during the function definition, you assign the function
directly to a variable or use it as an argument in another function.

let subtract = function(a, b) {


return a - b;
};

console.log(subtract(10,6));//4

3. Arrow Function:

An arrow function in JavaScript is a concise way to write a function expression. It was


introduced in ECMAScript 6 (ES6) and provides a shorter syntax compared to traditional
function expressions.
let multiply = (a, b) => a * b;
console.log(multiply(5,8));//40

4. Immediately Invoked Function Expression

An Immediately Invoked Function Expression (IIFE) is a JavaScript design pattern where a


function is defined and executed immediately after its creation.

The primary purpose of using an IIFE is to create a new scope for variables, preventing
them from polluting the global scope.

Syntax :(function() {
// code here
})();
Ex:
let no1 = 5;
let no2 = 6;

(function sum(num1, num2){


let result = num1 + num2;
console.log(result);
})(no1,no2);

5. Callback Function:

 A callback is a function passed as an argument to another function.


 This technique allows a function to call another function.
 A callback function can run after another function has finished.

function f(num1, num2, callback){


var result = num1+num2;
callback(result)
}
function showresult(cb){
console.log(cb);
}
f(10,20,showresult);

6. Recursive Function:

A recursive function in JavaScript is a function that calls itself during its execution.

function factorial(n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
console.log(factorial(5));//120
7. Higher-Order Function:

In JavaScript, a higher-order function is a function that takes one or more functions as


arguments or returns a function as its result.

Essentially, it treats functions as first-class citizens, allowing them to be used as values.

1. By taking them as argument

function x(){
console.log("higher order as function");
}
function y(x){ //y is a higher order function
x();
}
y(x);

2. By returning them

function printfunc(){
return function(){
console.log(" From return type function.")
}
}
var x = printfunc();
x();

8.Generator Function:

A generator function in JavaScript is a special type of function that allows you to control
the execution flow and pause/resume it at certain points.

Generator functions are defined using the “function*” syntax and use the “yield” keyword
to produce a sequence of values lazily, one at a time.

function* generateSequence() {
yield 1;
yield 2;
yield 3;
}
Note: The yield operator is used to pause and resume a generator function.
let generator = generateSequence();
console.log(generator.next().value); // Output: 1
console.log(generator.next().value); // Output: 2
DOM TREE

The document object is the root of DOM tree.

DOM

 The every html element is considered as a node (js object) in DOM.


 DOM allow to modify the document content rendered by the browser without
reloading the page. Therefore DOM helps to make a web page dynamic.

Note:
 Any modification done using DOM is not updated to the original html document.
Therefore, once we reload a page all the modification done using DOM will be lost.
 We can write the content on the browser dynamically with the help of write and
written method of document object.
Ex:
To display a message on the browser page from java script code:
document.write(“hi”)
 Dom is an API provided by the browser.
 Dom is not a java script, it is built using java script.
 Dom is an object oriented representation of html file.
 Every time an html document is given to the browser, it automatically generated it
can be accessed and modified using the root node document in JavaScript.
Uses of Dom:
1. Change and remove element in the Dom on the webpages.
2. Change and add CSS Style to the element.
3. Read and change content of the webpage.
4. Create new elements
5. Attach event listener.

To Create the Element in the DOM

METHOS:

Create Element
For this method we need to pass the tag name of an element as string, it returns the
element.
Append:
For this method we have to append the element to the body once it is created by
DOM CreateElement.
Append Child:
For this method we have to append children the element to the body once it is
created by DOM CreateElement.
TO OBTAIN THE ELEMENTS FROM DOM:

Methods of Dom:
1. getElementById():

 For this method we need to pass the ID of an element using a string, it


returns the first element specified ID.
Syntax:
document.getElementById():

2. To fetch an element using ‘name’ attribute:


Syntax:
getElementByName():

 We need to pass the name of an element as a string.


 It returns a node list, which is similar to array but not an array.
 If there is no element with the given name, then it returns empty node list.

Ex:
let e1 = document.getElementByName(“heading”)
console.log(e1[0]);
console.log(e1[0].textContent);
e1[0].textContent = ‘welcome’;
console.log(e1[0].textContent);

3. To fetch an element from DOM using the class name:


getElementByClassName():

 Pass the class name as a string.


 It returns a node list, containing all the element matching the given html
collection, which is similar to array but not an array.
Syntax:
document. getElementByClassName(“class”):
Ex:
let e3 = document.getElementByClassName(“divStyle1”):
console.log(e3[0].textContent);

4. To fetch an element from the DOM using the tag name:


getElementByTagName():

 We need to pass tag name as a string.


 It returns an html collection all the element matching the given tag name.
5. To fetch the element from the DOM using CSS selector:
We can select an element from DOM using CSS selector with the help of
1. querySelectorAll
2. querySelector
Note:
We need to pass a CSS selector as a string
Query selector returns the reference of first element found.
Query Selector All returns a node list of all the element found in the original order.

DOM PROPERTIES:

1. firstElementchild
2. firstchild
3. lastElementchild
4. lastchild
5. children[0]
6. parentElement[]
7. nextSibling
8. nextElementSibling
Note: To access node use “ [values] ”.

EVENT:

Event is performed by end user on a web page.


Event is handled by EventHandler/EventListener.
An end user can perform different kind of event such as
1. mouseEvent
2. keyboardEvent
3. WindowEvent
4. Scroll, etc.

Event

EventHandler/EventListener

Event Event
As an attribute As a DOM method

1. onclick Syntax:
2. onfocus addEventListener(“event”,call
back function, boolean)

HTML Event Attributes: https://www.w3schools.com/tags/ref_eventattributes.asp


Event Listener:
EventListener or EventHandler is a function which executes the task when an event is
occurred on the most specific element.

Event Flows
Event Capturing: Event handler that gets triggered whenever we click on an element, like
onclick.
Event bubbling: In event bubbling the event starts at the target element (most specific
element) and then flows in the upward direction of the DOM tree.

Event Propagation (flow of event object):


Event propagation has 3 phases
Phase 1: event capturing occurs, it provides to intercepts (come between and do
something) the even.
Phase 2: actual target receives the event.
Phase 3: Event bubbling occurs, it provide an opportunity to have a final response to an
event.

13/10/2023

ASYNCHRONOUS:

Asynchronous describes the relationship between two or more events/objects that do


interact within the same system but do not occur at predetermined intervals and do not
necessarily rely on each other's existence to function.
Start something now and finish it later.

Statement 1
Takes
time
Statement 2 Database

Statement 3

Statement 4

Callback
async - always return a promise

let reach = new Promise((resolve, reject)=>{


const reached =true
if(reached){
setTimeout(resolve,3000,"Tamil Reached");
}
else {
reject("Tamil not reached")
}

async function fn(){


return "hello";
}
console.log(fn());

// fn().then((msg)=>console.log(msg)) // resolve method

async function asyncstatus(){


console.log("hi...");
res = await reach;
// await is only valid in async, so await must be used inside in async function

console.log(res);
console.log("Bye");
}
asyncstatus();

ARRAY:

Array is a huge block of memory which is used to store multiples values of different types.

To create an array
a. In JS array is an object.
b. We can create array object in different ways

1. Using array literal[]


2. By creating an instance of array, using new operator
3. By creating an instance of array, using new operator and initializing the element
using array constructor.
Continuous block of memory.
To store multiple elements. Length of
array

1 2 3 4 5
6
Const obj: Java Web J2EE SQL Python

0 1 2 3 4
Index value
/Reference
value

Associative array:
In JS array is not in type of out associate array.
Use always Const.

Associative array is not recommended


--------------------------------------------------------------
const arr1 = []

arr1["one"] = "Java"// not recommended


arr1["two"] = "Web"// not recommended

console.log(arr1[0]);
console.log(arr1[1]);
console.log(arr1);

arr1[0] = "Java"// recommended


arr1[1] = "Web"// recommended

console.log(arr1);
--------------------------------------------------------------
Using array literal []:

Syntax:
Let arr = [value 1, value2, value3…] here ‘arr’ is the literal which stores the address of
array object.

Ex:
let arr = [10,20,30];
console.log(arr)

By creating an instance of array, using new operator:

Syntax:
let arr2 = new array(): here ‘()’ is function call

‘array()’ array function constructor


Array – anything starts with capital A it is class
() – constructor / constructor function which is having same name as class.
‘new’ is keyword, which create new object

JavaScript array constructor (new keyword)

Eg:

Let arr3 = new array (10,20,30);


Creating an array object and passing data to array and address of array of object is given
to arr3.

To access the array element:

We can access array elements with the help of array object reference, array operator &
index.

Syntax:
array_obj_ref[index]

Index: it is a number starts with zero and ends with the (length of array object - 1)

Ex:
let hobbies = [‘reading’,‘writing’,‘playing’,‘cricket’]
console.log(hobbies[1]);//writing

Adding elements into the array object:

var car = "volvo"


var ca1 = "ford"

const subject = ["Java","Web","J2EE","Sql","Python"]


console.log(subject[0]);

console.log(subject.length);//To know the length of the array


console.log(subject.length-1);//Access the last memory
console.log(subject[subject.length-1]);//Access the last element value

--------------------------------------------------------------
Iterate element inside an array

const subject = ["Java","Web","J2EE","Sql","Python"]

let sub_leng = subject.length;


console.log(sub_leng)

for (i=0; i<=sub_leng-1; i++){


console.log(subject[i])

}
--------------------------------------------------------------
To append to order list

const subject = ["Java","Web","J2EE","Sql","Python"]

let sub_leng = subject.length;


console.log(sub_leng)

let orderlist = document.createElement("ol");


document.body.append(orderlist)

for (i=0; i<=sub_leng-1; i++){

let listitem_new = document.createElement("li");


orderlist.appendChild(listitem_new);
listitem_new.textContent = subject[i];

console.log(subject[i])
}

--------------------------------------------------------------
Array as homogeneous and hetrogeneous

var data_type = [
"smith",
99,
9n,
true,
false,
undefined,
null,
{
ename: "smith"
}
["smith"],
function(){

console.log("array js")
}

];

var type_lenght = data_type.length;


let temp = 0;
for(i=0; i<type_lenght;i++){

if(typeof data_type[i] == "bigint"){


temp++;
}
}

console.log("No.of bigint present in array: "+temp)

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

var student1 = "smith"

var student2 = "Rose"

const student_detail = [student1,student2];

console.log(student_detail[0]);

--------------------------------------------------------------
Task:

let num1 = Number(prompt("Please enter your num1"));


console.log(typeof num1)

let num2 = Number(prompt("Please enter your num2"));


console.log(typeof num2)

let Option = prompt("Press\n 1:Addtion \n 2:Subtraction");

if(Option == 1){

var addition = num1+num2;


alert(`The sum of ${num1} and ${num2} is ${addition}`)

}
else if(Option == 2){
var subtraction = num1-num2;
alert(`The difference of ${num1} and ${num2} is ${subtraction}`);

else{
alert("Kindly enter correct option")
}

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

Rest and spread operator / Destructuring of array

function sum(a,...b){
console.log(a)
console.log(b)
}
sum(10,20,30,40)

const obj = ["a","b","c"]


const obj1 = ["d","e","f"]

const result = [...obj,...obj1]


console.log(result)

const students = ["smith","rose", "Daivd"]

console.log(typeof students) //Object

const [boy1,girl1,boy2] = students

console.log(boy1);
console.log(boy2);
console.log(girl1);
console.log(boy2);

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

for - of/for - in

var arr = ["chennai","Banglore","Pune","Kolkata","Coimbatore"]

for(var x of arr){
console.log(x)
}

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

var arr = ["chennai","Banglore","Pune","Kolkata","Coimbatore"]

var ol = document.createElement("ol");
document.body.append(ol);

for(var x of arr){
if(x.length %2 ==0){
var li = document.createElement("li");
ol.appendChild(li);

li.textContent = x;
}
}

--------------------------------------------------------------
var arr = ["chennai","Banglore","Pune","Kolkata","Coimbatore"]
for ( var x in arr){
console.log(x)
}

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

var arr = ["chennai","Banglore","Pune","Kolkata","Coimbatore"]

var even = document.createElement("even")


document.body.append(even)

for (var x in arr){


if (x%2 ==0 && x!=0){
var li = document.createElement("li");
even.appendChild(li)

li.textContent = arr[x] ;

}
}

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

Way to create an array

There are 2 ways to create an Array


1. Array Literal
2. New keyword
3. Passing the element directly

1st way to create an Array


const arr = ["arrayliteral"]
console.log(arr)

2nd way using new keyword


const arr = new Array();

console.log(arr)

arr[0] = "simth";
arr[1] = "rose";
console.log(arr)

3rd way using new keyword initializing some value


const arr = new Array(5,2)

console.log(arr);

const arr1 = new Array(5)


console.log(arr1)

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

var hobbies = [
"football",
"singing",
"reading",
"cooking",
"travelling",
"sleeping",
"house cleaning",
"driving",
"cycling",
"trekking",
"reading"
];

1. lenght method

console.log(hobbies.length)//11

2. Sort method: sort the element in alphabetical order

console.log(hobbies.sort());

3.Push method: push the element in the tail of an array

hobbies.push("Swiming", "cricketing")
console.log(hobbies)

console.log(hobbies.push("dancing"))

4. PoP method: Remove last element from the tail of an array

hobbies.pop();
console.log(hobbies);

5.unshift method :to add element in 1st index

hobbies.unshift("firstElement","secondElement")
console.log(hobbies)

6. shift method: remove the 1st element from the tail of an array

hobbies.shift();
console.log(hobbies);

7. isarray method: To check given array is array or not

let isarray = Array.isArray(hobbies)


console.log(isarray); //true
8.includes method : To check weather the element is present or not

let check_elem = hobbies.includes("football");


console.log(check_elem);

9. indexof method: To find the index of element of an element

let find_index_element = hobbies.indexOf("reading")


console.log(find_index_element); // it will returns 1st index if the element which is
repeated

10. splice method

Method accepts 3 values


Splice will modify the original array
Splice will not accept negative values

console.log(hobbies)

let splice1 = hobbies.splice(2,4,"smith")


console.log(splice1)
console.log(hobbies)

11. slice method

Method accepts 2 values


Splice will not modify the original array, but it will create a new array
Splice will accept negative values

console.log(hobbies)

let slice1 = hobbies.slice(2,4);


console.log(slice1)
console.log(hobbies)
Negative values : It will slice from last element of array

let slice1 = hobbies.slice(-4,-2);


console.log(slice1)
console.log(hobbies)

12. tostring method : to convert into string

let arr = hobbies.toString()


console.log(arr)

13. reverse method: to reverse the elements in an array

let rev = hobbies.reverse()


console.log(rev)

Map, reduce, and filter are all array methods in JavaScript. Each one will iterate over an
array and perform a transformation or computation. Each will return a new array based on
the result of the function

Map

The map() method is used for creating a new array from an existing one, applying a
function to each one of the elements of the first array.

Syntax

var new_array = arr.map(function callback(element, index, array) {


// Return value for new array
[, thisArg])

In the callback, only the array element is required.


Usually some action is performed on the value and then a new value is returned.

const numbers = [1, 2, 3, 4);


const doubled numbers.map(item => item 2);

console.log(doubled);

Filter

The filter() method takes each element in an array and it applies a conditional statement
against it.

If this conditional returns true,

The element gets pushed to the output array. If the condition returns false, the element
does not get pushed to the output array.
If the condition returns false, the element does not get pushed to the output array.

var new_array = arr.filter(function callback(element, index, array) (


// Return true or false
[, thisAre])

Examples

In the following example, odd numbers are "filtered" out, leaving only even numbers.

const numbers [1, 2, 3, 4];


const evens numbers.filter(item-> item % 2 --- 0);
console.log(evens); // (2, 4)
Reduce

The reduce() method reduces an array of values down to just one value. To get the output
value, it runs a reducer function on each element of the array.

The callback argument is a function that will be called once for every item in the array.
This function takes four arguments, but often only the first two are used.

1. Accumulator: the returned value of the previous iteration


2. Current Value: the current item in the array.
3. Index: the index of the current item
4. Array: the original array on which reduce was called

The initialValue argument is optional. If provided, it will be used as the initial


accumulator value in the first call to the callback function.

Examples

The following example adds every number together in an array of numbers.

const numbers [1, 2, 3, 4]; =


const sum = numbers.reduce(function (result, item) {
return result + item;
), 0);

console.log(sum);

Object

JavaScript is an object Oriented programming language.


A JavaScript object is like a real-world entity (States) having and behaviour.
JavaScript is template based and we can create object without the need of having a class.

Create a JavaScript Object

There are 3 different ways

1. literal
{name : value}

Example:

Var student = {
name: “chris”,
age: 21,
studies: “computer science”
};
2. new keyword

var obj_name = new Object();

Example:

Var student = new Object();


name: “chris”,
age: 21,
studies: “computer science”

3. Object constructor

Function stud(name,age,studies){

this.name = name;
this.age = 21;
this.studies = studies;
}

var student = stud(“chris”,21, “computer science”);

OBJECT:
1. Any substance which has its existance in the real world is known as OBJECT.
2. Every object will have states(attributes of feeds which describe them).
3. Every object will have actions (behaviours)
4. JavaScript object are just a collections of named values, these named values are
usually referred to as properties of object.

EX:
1-car:
states of car: model,color,price
actions of car:accelarate, brake, start, stop

2.webpage:
states 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 -The actions of
real world object are represented using METHODS (FUNCTIONS).
1. In javascript object is a collection of attributes and actions in the form of
key&value pairs enclosed
2. within curly braces()
3. Key represents properties/attributes of an object
4. Value represents state of an object.

To access object property in two ways:


1. Dot notations
2. Using square brackets
3. You can pass any datatypes as a value for object:
4. Literals (value type)
5. Variables/expression
6. Function
7. Object
8. Array

In JavaScript, we can create je object in 3 different ways:


1. Object literal ()
2. Using a function
3. Using a new keyword

1. Object literals

const obj = {
name: "sheela",
age: 24,
profession: "software engineer", };
console.log(obj);
console.log(obj.name)
console.log(obj.salary = 200)
delete obj.profession

2. Using function

function Obj1(name, make, model) {


this.name = name)
this.make make;
this.model = model;
let obj2 = new Obj1('camlin, india, 05 / 16 / 28) console.log(obj2)

3.Using new key-word

const person = new Object();


person.firstName = "testFirstName";
person lastName = "testLastName";
console.log(person)
Methods in objects

const obj = {
name: "sheela",
age: 24, profession: "software engineer", };
console.log(obj))
//to add key: value pair into an object
obj_salary = 2000; //add salary to object console.log(obj);
obj.name = 'smith'; // to change value of name is replaced with 'smith'
console.log(obj)
//to delete a key from an object
delete obj salary;
console.log(obj) //salary will be deleted

Object.assign();

Syntax
Object.assign(target, sources);

The Object assign() method is used to copy the values

const abj1 = {
name: "sheela",
age: 24, profession: "software engineer", };
let source = (
living: "bangalore",
company: "test yantra", };
console.log(Object.assign(objl, source));
console.log(obj1)

Values()

const obj = {
name: "sheela",
age: 24,
profession: "software engineer",
console.log(Object. values(obj)) console.log(obj)

Keys

const obj = {
name: "sheela",
age. 24,
profession: "software engineer", };
console.log(Object.keys(obj)) console.log(obj)
seal
seal- it won't allow to add any more object keys and values
const obj = {
name: "sheela",
age: 24,
profession: "software engineer",
console.log(Object.seal (obj));
obj.salary= 200;
console.log(obj) obj.name = "smith"
console.log(obj)

Seal

It won't allow to add any more object keys and values

const obj = {
name: "sheela",
age: 24,
profession: "software engineer",
console.log(Object.seal (obj));
obj.salary= 200;
console.log(obj) obj.name = "smith"
console.log(obj)

Entries to converts the objects into an array

const obj = {
name: "sheela", age: 24,
profession: "software engineer", };

var s1 = Object.entries(obj);
console.log(s1)
console.log(s1.flat())
var arr = [1, 2, 3, 4, 5,[[[[6]]]]]
console.log(arr. flat (4))

Freeze-it won't allow to modify any more object keys and values

const obj = {
name: "sheela",
age: 24,
profession: "software engineer",
console.log(Object.freeze(obj));
obj.profession = "tester";
obj.salary = 200; console.log(obj);

Note:
1. If the key is not present in the object then we get 'undefined' as the value.
2. The objects in JavaScript are mutable (state of the object can be modified) in
nature.

You might also like