0% found this document useful (0 votes)
8 views

JS Notes

JS

Uploaded by

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

JS Notes

JS

Uploaded by

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

JAVASCRIPT

SJS
JAVASCRIPT
It is a Scripting language works as both front and back end. Mainly using for front end. It creates dynamic page by providing
behavior or functionality to a web page. (By writing logic)
Backend: Node-JS, Angular-JS, React-JS
 Node.js: it is combination of C++, JS v8 with bundle of method and rules, it is an advanced version.

JS is a Scripting language, every scripting can be a programming language, but every programming language is not a scripting
language.
HISTORY:
 Introduced Brenden Erich, May 1995, were he worked in Netscape, he built JavaScript within 10 days.
 First Moka or Mocha later it will called as Live script and later it is known as Java script.
JS code runs on browser, so browser act as client. So it is called client-side language
JavaScript is used to make webpage dynamic
Uses of JavaScript:
 It is used to build web application, desktop application and a game development.
 It is used to display day/date and time.
 It is used to animate the elements.
 It is used for dynamic drop-down. (drag-drop)
 Webpage performs actions without loading the webpage
 Dynamic webpages are changes the happen on the webpage after the webpage has been loaded
Without refreshing the page.
ECMA script
 ECMA European Computer Manufacturer Association
 ECMA standard created for JS
 Version 6, it gives blue print to JavaScript.
 The Standard version of JS is ECMA script.
 JS and ECMA script both are same.

Why JS?
1. Scripting language
2. Light weight and purely object based language
3. JS is high-level language which gets executed on the browser, to execute JS instructions it is mandatory to translate JS
instruction into machine understandable language, this job is done by JS engine
4. client-side language
5. JS is loosely typed and dynamic typed language - To giving the functionality to the webpage, without reloading the page
It is case-sensitive (but html and CSS are casein sensitive)
6. It is interpreted language - means it is interpreted line by line or execute line by line
7. It is synchronous: it is follows only one stack; example books arrangement in library, (LIFO) Last in first out: memory
representation
Difference between Java and JavaScript
Sl.no Java JavaScript
1. It is a programming language It is a scripting language
2. It is multi-threaded It is single-threaded
3. it uses more memory it uses less memory
4. It runs on JVM It runs on browser(JS engine)

1
5. It is not completely object It is purely object oriented.
oriented. Because, it as
primitive data-type such as
byte, int, short, Boolean, float,
double, char. Which is not
object.
6. It is strictly/strongly typed It is weekly typed
7. It Cannot be modified. Memory It can be modified.
is constant.
ex: int a=20; once the memory is
allocated means cannot be
modified,
8. It is independent language to It is dependent language (run on
run and execute browser)

 To write JavaScript there is opening and closing tags. <script> </script>


Browser:
 It is application which behaves like client
 Browser Itself acts like a complier or interpreter
 Browser gives an environment for JS to run
 Browser has a sub application called as JS engine
 JS engine responsible to translate JS instructions into machine understandable language within the browser
 We need JS engine to execute JS
 Every browser will have a JS Engine to run the JS code. Therefore browser becomes an environment to run Javascript

In browser we have sub-apps:


 Console
 Timer
 JavaScript engine
 Datatypes

List of JavaScript Engines:


 Chrome: V8 (Version 8 fastest and most efficient according to industry)
 Firefox: Spider monkey
 Safari: JavaScript core
 Microsoft-edge/Internet Explorer: Chakra
Can we run Js outside a browser?
Yes we can run JS outside the browser with the help of Node
Node:
 Node is a bundle of Google’s V8 Engine and built in methods using C++
 It serves as an environment to run JavaScript outside the browser
 Node is an environment to execute JS without the help of a browser

Characteristics of JavaScript:
 It is Purely object oriented means Object based
 It is Synchronous (single threaded, it is having one stack)
 It is case-sensitive, JS is cases insensitive only small letter
 It is interpreted language
 It is platform independent
 It is JS uses JIT (combination of compiler and interpreter) just in time compiler (it reads the user input, run and execute
then and there itself. Just like scanner class in java)

2
 Object oriented language do not have in-built object.
 Object based languages are having in built objects.

Note:
 JavaScript is a high level language. User can easy understandable easily.
 Browser application provides an environment too run JavaScript.
 We can run JS both inside the browser and outside the browser. Outside browser using Node.js.

How JavaScript works:

AST (Abstract Machine level


Syntax Tree) language

Browser
Parser

Deployed on
Console (inspect)

 AST: Abstract Syntax Tree and PARSER: Converts HTML code to AST
Browser – Parser—AST—Machine Level Language –Console

How to execute JS on browser


1. Console
2. Types
a. Internal
b. External
3. Extension(.js)

 Externally :<script src=""></script>


 if you give or link the script tag inside the body tag: so the browser will execute tags line by line, first enters to the body it
goes to functionality, and it should be at the end of tag before closing body tag.
 If your write in head tag some browser not supported.
 First open and close the script tag.

 Internally :<script></script>
 We can write either inside the body or inside head also, if script is used in head tag means don not use in body tag
 While linking the CSS use inside a head : <link rel:"style sheet", src:""></link>
 Vue.JS, React.Js, Angular.JS these are all libraries
 Dynamic: some action after loading
 Static: no action after loading

3
JS Engine:
Browser and JS engine
Browser is a Google chrome, JavaScript engine is visual studio (most fastest) Browsers Engine
 Google chrome-V8(most fastest)
 Firefox- Spider monkey
 Internet explorer-chakra
 Safari-JavaScript Core
It will converts the JS CODE to machine level instruction.

Object it is block of memory which has states (variables) and behaviour (methods), and stores in key and value pair.
Console.log("Hello World")
Console. log ( “data” );
Argument
Function
Operator
Object

Console: It is object in JavaScript. It will help you (user/programmer) to uses variables and functions present in the object.
Log: it is a function which accepts arguments. Log is member of console. (Present inside the console)

 console is object
 (.)dot is operator
 log is function
 It is used to print a statement in console using inside VS.
 console it is mainly used to JS code to execute, we can write,
 We can print. it will stores values.
 To print a statement in Window we use document.write
 document.write("Hello World")
 Typeof: it is a operator which gives what type of data is using. Ex: var a= 10; console.log(typeof a);

First code:
<html>
<head>
<title> Document</title>
</head>
<body>
<h1> Progarm2 </h1>
<script> console.log(“Hello World”)</script>
</body>
</html>

Use <script src=”path”></script> - to include all JS files


To execute JS on browser
1. We can execute JS instruction directly in the console provided by the browser
2. We can execute JS instruction by embedding it in html page

4
a. inline
b. externally
a. inline: With the help of scripting tag we can embedded JS instruction syntax
Internal JS : JavaScript code should be written inside a HTML document itself and it should be written inside the body.
<html>
<head></head>
JavaScript code
<body>
<script>
document.write(“Hello”);
</script>
</body></html>

Create a html.file.
Console.log(); - to print the statement
Ex:
<script>
//<script>console.log("HELLO WORLD OF JS");
</script>
OUTPUT: HELLO WORLD OF JS
-To clear the content in Console

It reads in browser
We will get output on the browser
Ctrl+shift+I (or) Ctrl+shift+J –to get Console window
We can perform operation of arithmetic in console directly (it is internal JS)

<html>
<head>
<title> Document</title>
</head>
<body>
<h1> Progarm2 </h1>
<script> console.log(“Hello World”)</script>
</body>
</html>

b. External:
1. We can create a separate file for JS with extension .js
2. Link the JS file with html file using the src attribute of script tag
Syntax:
<script src=”path/ filename.js”></script>

5
External JS:
 We can create separate file for JavaScript with the extension .js
 Link the .js file within hTML page by using src attribute of script tag.
<script src="G:\WEB\JS\index.js">

</script>

Extension
Ex: filename: Index.js Filename
Print the statements:
console.log("Hello");
console.log("HELLO WORLD OF JS");

To print new statement in next line in the console we use \n (backslash n)


Console.log(“ My name is : \n Alex”);
//with variables
var str= “I Love my country:\n INDIA”;
console.log(str);

Tokens in JS:
Smallest element/unit of any programs/ programming language.
1. Keywords
2. Identifiers
3. literals.

1. Keywords: are the predefined reserved words which can be understandable by JS engine.
Ex: var a=10:
here, var is keyword
Rules:
 keywords cannot be used as identifiers
 every keyword must be in lower case
 example if, for, let, null, while

2. Identifiers: Name given by the programmer to the components of JS like variable, functions, class and so on.
var a=10: here a is a identifier
Rules:
a. An identifier cannot start with a number
b. no other special characters used except ‘$’ and ‘_’
c. we cannot use keywords as identifiers

3. Literals: values or data used in program


var a=10:
here, 10 is value

6
DataType:
It is a type of data, every variable has datatype that represents what kind of data is being stored in a variable.
Types of Data Type: Primitive Data type, Non -Primitive Data type
 Primitive Data type: it is called as in built data type or pre-defined data type provided by JS language and it is immutable.
Types: Number, String, Boolean, Null, Undefined, BigInt, Symbol
 Non -Primitive Data user defined data type, it is also called as reference type, and created by programmer and it is mutable.
Types: Arrays, objects and functions etc.
 Mutable: can be change
 Immutable: cannot be changed
While using identifier inside console, do not use double quotes.
Primitive Data type:
 Number: to print number, range from (-2 power 53-1) to (2 power 53-1)
 String: In JS represents a string in ""{double quotes), ''(single quotes),``(back ticks is used to print multiple statements)
 Boolean: it can hold only two values either true or false
 Undefined: a variable for that the value is not assigned. Ex: var j;console.log(j);//Undefined
 Null: null accepting space. it is an empty space. it reserved a space. typeof null is object.
 BigInt: it is a datatype, if the number exceeds 150 numbers, we use suffix 'n' with that number to define BigInt. number
less than 150 will be considered as Number data type. 1- number,1n- BigInt.
 Symbol: it is a datatype, to give or to store or save a unique value. Ex: var a1=Symbol();
 Object: Everything like int, string and so on, will be considered as object in JS type of Symbol() is function.
According to Javascript all the types except object is considered as Primitive data types object is considered as non-primitive
type.

Non-Primitive Datatype:
Arrays, functions and objects
Arrays: array is a single value, But in JS we use to store different elements i.e., heterogeneous value.
Representing array in square braces []
Function: used to perform the operations.
Advantage: 1. code reusability
2. code extensibility or less coding

Representing the function:


function keyword,
function name (){
statements or code
}
eg:
function functionname(){
//code
}

Typeof Operator:

7
 It is a keyword used as an unary operator, to identify the type of data.
 Syntax: typeof value
 Example:
Console.log(typeof “done with file structure”); //string
Console.log(typeof “done with file structure”); //string
Console.log(typeof “done with file structure”); //string
Console.log(typeof 47); //number
Console.log(typeof true); //Boolean
Console.log(typeof false); //Boolean
Console.log(typeof null); //Object
Console.log(typeof undefined); //undefined
Console.log(typeof 1n); //BigInt

typeof null is never null it is considered as object

Console.log(typeof console) = Object


Console.log(typeof log) = Undefined
Console.log(typeof 5) = Number
Console.log(typeof 5.5) = Number
Console.log(typeof -5.5) = Number
Console.log(typeof -5) = Number

 Variables: it is like a container, which is used to store a value in a database. Variables named block of memory, In JS variable
is loosely typed and dynamically typed
 In JS variables are not strictly typed, it is loosely typed or dynamically typed, so it is not necessary to specify the data type
during variable declaration.
 In a variable we can store any type of Value
 it is mandatory to use the variable, before using it.
 Syntax for Declaration: variable and identifier i.e. var identifier, let identifier, const identifier;EX: var a=10;
Ex: var a=10;
Ex: let b;
b=20;
console.log(b);

Ex: const c=30;


console.log(c);

var, let, const these are standard keywords in JS.


 In var: declaration and initialization, re-declaration and re-initialization is possible.
 In let: declaration and initialization, re-initialization possible. Re-declaration is not possible.
 In const: declaration and initialization and it should done at a time. Re-declaration and re-initialization is not possible.
When a variable is declared in JS, JS engine implicitly assigns undefined value to it.
Interpolation means ${name} dollar symbol with value, using back tics we define interpolation
Ex: Write a JS code to store your following details, Name, age, gender, degree, aggregate and display them on the console.
Solution: var name=’Alex’;
var age=23;
var agg= 7.0;
console.log(`My name is ${name}, I’m ${age} years old and my aggregate is ${agg}`);
var a; Declaration statement
a=10; Initialization / assignment- giving or assigning a value to a

8
output: My name is Alex, I’m 23 years old and my aggregate is 7.0

Var:
 It is global scope.
 For var we can declare variables with the same name but it will access recently used variables.
 Variable declared using var can be hoisted it does not belongs to TDZ.(we can use before initialization)
 Ex: console.log (a) // hoisting or undefined
var a=10;
console.log (a)//10
Console.log(a) // undefined
var a=10;
Console.log(a)//10

let:
 it is a local scope
 we cannot declare two variable with the same name within a block
 variable declared using let we can hoist, but it belongs to TDZ (cannot be used before initialization)
 Ex: console.log (a) // unresolved reference error
var a=10;
console.log (a)//10
Console.log(a) // it shows an error message as reference error
let a=10;
Console.log(a)

Const:
 Constant value or fixed value like pi..
 it is a local scope
 the variable declared using const, it cause TDZ
 Ex: console.log (a) // unresolved reference error
var a=10;
console.log (a)//10
Console.log(a) // it shows an error message as reference error
const a=10;
Console.log(a)

Understanding Execution in JS
Everytime when JS Engine runs a JS code, it will first create a global execution context(GEC).
GEC: Global Execution Context:
JS engine runs JS CODE first it will creates space or memory is called global execution context.
GEC has two parts:
Variable area: all declared variable is default value is undefined, after assigning it will be override or replace with new value
or all variable declaration will be in variable area

9
Functional area or execution area: except declaration variable, all other will goes to functional area. Like initialization,
methods etc. or all the statements except variables declaration.
For all data types, before declaration it is undefined,
If not writing any keywords in programmer then default value of keyword is var.
JS engine has 2 phases:
Phase 1: JS engine read all code in the memory is allocated for declaration, will reads that all data from top to bottom order
it will execute in GEC and twice. Or JS engine reads code in top to bottom order in Variable area
Phase 2: read all the codes twice

Varaible area Functional area


A undefined and after assigning it will replace to A=10 A=10
B undefined and after assigning it will replace to B=20 B=20
C=30
Only declaration Clog(A) print statement
Clog(B) print statement
Clog(C) print statement

Clg(a); Variable area Function execution area


var a=10;

Clog(a);
a= undefined Clg(a)
Time Gap b/w
declaration and
initialization is TDZ
Index.js a=10 var a=10
a= 10 Clg (a)

Hoisting: JS allows a programmer to use a member or variable before declaration statement this feature is called hoisting.
Using console.log(a) statement before declaring the variable.
We can do hoisting for var, let, and const.
 For var – we get output as undefined because, it has global scope
 For let and const – we get reference error because it has local scope.
Ex:1-
console.log(a); //undefined- is called hoisting
var a=10;
console.log(a);//10
Variable hoisting: it is not possible
Functional hoisting: it is possible
Ex:2-
//using test before declaring
Console.log(test);
var test;
Output:
node/tmp/xtAh947sUt.js
undefined
Types of Hoisting:
1. Variable Hoisting:

10
In terms of variables and constants, keyword var is histed and let and const does not allow hoisting.
//program to display value
var a;
a=5;
console.log(a);
// Output 5

2. Function Hoisting:
A function can be called before declaring it.
//program to print the text
greet();
function geet() {
console.log(‘Hi, there.’);
}
// Output Hi, there..
Temporal Dead zone(TDZ):
It is a time gap between the variable which is created/ declared and initialized is known as TDZ. Or time gap between
declaration and initialization.

Output methods:
5 methods; Alert, Prompt, Confirm, Console.log, document.write
a. Alert: it gives alert window.
Ex: var d=10;
alert(d)
b. prompt: to get input from the user we use prompt
ex: Write a code to read text from the browser using the prompt and display number of characters present in the text
var str=prompt();
var n= str.length;
console.log( str);
console.log( `number of characters in text are ${n}`);

c. Waring:
Console.warn(“this is waring message”)
- It shows warning
-
d. Error:
Console.error(“this is error”);
- It shows error message

Operators in JavaScript:
Operators are the symbol which perform some specific task.
 Arithmetic operator
 Assignment operator
 Comparison operator

11
 Logical Operator
 Conditional operator : true/false
Arithmetic operator:
Which performs arithmetic operation such addition, subtraction, multiplication and division.
Ex: var a=10;
var b=20;
console.log(“sum of+”, a+b);//30
Assignment Operator: (a+=b) //30
Assignment =
Additional assignment +=
Subtract assignment -=
Multiplication assignment *=
Division /=
Modulus %=

Logical Operator: AND, OR, NOT

AND (&&) : if all values are true then


T T T
T F F
T T F
F F F

Ex: var a=10;


var b=20;
console.log(a>b&&b<a)
console.log(a>b&&b>a)
console.log(a<b&&b<a)
console.log(a<b&&b>a)

 OR(||)

T T T
F T T

12
T F T
F F F

Ex: var a=10;


var b=20;
console.log(a>b||b<a)
console.log(a>b||b>a)
console.log(a<b||b<a)
console.log(a<b||b>a)

 NOT(!)
T F
F T
Ex: console.log (!(a>b)
console.log (!(a<b)

Conditional Operator/ Ternary Operator: it is used for decision making

TRUE FALSE
( Conditon ) ? Expression 1 : Expression 2
Operand 1 Operand 2 Operand 3

Ex: var a=10;


var b=20;
(a>b)?a:b

Example: Program to find the status of the age


var age= prompt(“please enter the number”);
var status = (age >18) ? ‘major’ : ‘minor’;
console.log(status);

Comparison Operator or Relational Operator:


Operator Name
== Equal
=== Identical or Strictly Equal
!= Not equal
<> Not equal
!== Not Identical
> Greater than
< Lesser than
>= Greater than or equal to
<= Lesser than or equal to
==: equal to- check only the value
====: strictly equal to, check both the value and data type
Equal (==): it will check only the value.

13
var a=10;
var b=10;
console.log(a==b)
console.log(a===b)
Strictly equal or identical (===): it will check value along with the datatype.
var a=10;
var b=’10’;
console.log(a==b)//true here, it checks only value
console.log(a===b)//false here, it checks both value and data-type.

Unary operator: 1.Increment Operator, 2. Decrement Operator


1.Increment Operator
 post increment : it will increment the value but returns before increment it. Ex: a++
 pre increment: it will return the value but after increment it. ex:++a
2. Decrement operator:
 Pre decrement: ex: a- -
 Post decrement: ex: - -a

Typecasting or Type Conversion :


Type casting: Converting from one data type to another by JS engine explicitly
Type Coercion: Converting from one data type into another data type by JS engine implicitly when user used wrong data
type in expression.

Two types:
3. Implicit
4. Explicit

Example: console.log(5-"1");//4
console.log(5+"1");//51
here, string is converted to number and operation is performed,
 In JavaScript all non-zero numbers are considered as as true.
 Number zero(0), Null, undefined, NaN, empty string(“ “) are considered as false
A non empty string considered as true.
 While doing a logical OR (||)operator: whenever LHS and RHS is non Boolean it behaves different.
Step1: first converts the LHS value into Boolean
Ex: console.log(10 || 20);

Step2:if the converted LHS value is false then it returns the original value present in the RHS
Ex: console.log(0||20);//20
console.log(0||40);//40
Non Boolean: except Boolean data type
Non numeric value in the subtraction operation results in NaN
NaN : Not a Number
14
Type-casting: Converting from one data type to another by JS engine explicitly
Syntax: Number (data to be converted)
Conversion of any type to number
String to Number : clg(Number(“123”)); valid
a) If string is a valid number we get real number
b)If the string is any character then we will get number clg(Number(“a”));NaN
c)If we convert Boolean to number (false=0) (true=1)

Implicit: The process of converting one type of data into another type of data by JavaScript engine implicitly, when a wrong
type of data is used in the expression is known as implicit typecasting or coercion. Here, JS will converts
Ex: console.log(10+3)//13
console.log(10+’3’)//103
console.log(10-3)//7
console.log(10-‘3’)//7
console.log(10+’a’)//10a
console.log(10-’a’)//NaN (Not a Number)

NaN:
 it stands for Not a Number.
 Console.log(typeof NaN)//Number
 NaN=false
 It is a special type of number in JavaScript
 When string is trying convert into a number at that time we get output as a NaN.
 Any arithmetic operation perform with Na it is always a NaN.
 NaN is false with the help of conditional operator, we get to known the NaN as false.

Console.log(0)?true:false //false
Console.log(“”)?true:false //false
Console.log(Undefined)?true:false //false

 0,” ”,undefined, NaN, Null when all these are converted into Boolean it returns false.

Explicit Typecasting: it is a process of converting one date type into another type explicitly is known as Explicit Typecasting.
Ex: Console.log(10+2); //12
Console.log (‘10’+2);//102
Console.log(Number(‘10’)+2); // 12 Explicit Typecasting
Console.log(Number(‘10a’)+2); // NaN

String: Sequence of characters is String, In JS String can be represented using ‘ ‘ ,” “, ` ` .


Note:
1. The start and end of a string must be done with the help of same quote.(`”,” ‘,’ “, these are not allowed.)
2. If a text contains a single quote ten it can be represented using “ “.
15
Ex:
In normal text I’m a Software Engineer
In JS “I’m a Software Engineer”

In normal text “JS” is Awesome


In JS `“JS” is Awesome`

Backtick: A Backtick can be a multi-line string. String represented using backtick is also known as Template String.
The advantage of template string is we can substitute an expression in a string using ${expression}.
Var hobbies=`my hobbies:
1. Swimming
2. Cycling
3. Running
4. Gaming `;
Console.log(hobbies);
Output: my hobbies:
1. Swimming
2. Cycling
3. Running
4. Gaming

+operator: +operator behaves like a concat operator if the operand is a string.


Ex: console.log(“I’m ”+name+” and I’m “+age+” years old”);
Concatenation:
Number with addition with String- Concatenation

String Methods:
1.IndexOf()
Syntax: IndexOf(str/chr) user can give string or character, it will return index value.
Character which is not present in the string then the output will be -1. first occurrence value..
But it can take 1st and 2nd character too
2. lastindesxof()
3. search() is similar to indexof, it only first occurrence value. Accept the, first search character only one character. It not
accept two argument
4. Str.length:To check the length of the String
var str= "JAVA SCRIPT"
console.log(str.length);
5. Slice: To check the character in the index, using this we can extract some part of string. It will accept the first or start index
and last index. Last digit will be work as length- 1, if (5, 9) 5 to 9-1=8, we can pass both positive and negative value

var a = str.slice(0,4);
console.log(a);

6.Uppercase
var a= str.toUpperCase("script");
console.log(a);

7.Lowercase

16
var a = str.toLowerCase("java");
console.log(a);

8. Concat
Addition of two strings
var a="Java"
var b=" Script"
console.log(a.concat(b));

9. charAT : it specifies the position of the character


var str="JavaScript";
var char=str.charAt(1);
console.log(char);//a

10.charCodeAT: it converts to the ASCII value to the specified character


var str="JavaScript";
var char=str.charCodeAt(1);
console.log(char); //97

1. it repeat the string 3 times.


var char=str.repeat(3);
console.log(char);//JavaScriptJavaScriptJavaScript

11.replace(): it helps to replace the string.


var str='Pune to Bangaluru'
var char=str.replace("Pune", "Mangaluru");
console.log(char); //Mangaluru to Bangaluru

12.trim:It removes the space which is present at starting and endig position.
13.startWith
var car="JAVASCRIPT"
var char = str.startsWith(']');
console.log(char);

14.EndsWith
var car="JAVASCRIPT"
var char = str.endsWith(']');
console.log(char);

14. Split
Example 1:
var str='QSPIDER MYSORE';
var char=str.split('');
console.log(char);

Exampe 2:
var str='QSPIDER MYSORE';
var char=str.split(' ');

17
console.log(char);// (2)['QSPIDER MYSORE']

Example 3:
var str='QSPIDER MYSORE';
var char=str.split('| ');
console.log(char);// (1)['QSPIDER MYSORE']

15. Substring : substring () to extract the part of string, it is similar to slice but it won’t accept the negative value
16.Substr(): start index and length of the character to be extracted. It will accept negative value.
using subscript [] we can access the character.
var str='QSPIDER MYSORE';
var char=str.substring(0,5);
console.log(char);//QSPID

17.InString:
var str='QSPIDER MYSORE';
var char=str.indexOf('P');
console.log(char);//2

18.INCLUDES:
var str='QSPIDER MYSORE';
var char=str.includes('IN');
console.log(char);//false
var str='QSPIDER IN MYSORE';
var char=str.includes('IN');
console.log(char);//true

Decision Making statements in JS:


If, if else, else if ladder, switch
1. If
If(condition)
{
Stmt;
}

2. If else
If (condition)
{
Stmt;
}
Else
{
Stmt}

18
3. Else if ladder:
Syntax: if (condition)
{
Stmts;
}
Else if(condition)
{
Stmts;
}
Else if(condition)
{
Stmts;
}
.
.
.
Else
{
}
Switch case:
Syntax:
Switch(value)-> do not pass the conditions , pass the value
{
Case value:{
Stmnts;}
Case value:{
Stmnts;}
Case value:{
Stmnts;}
Default:
{
}
}
Case block is executed only when case value is matches with value.
Switch(1){
Case 1:{ clg (‘case1’);}
Default:{ clg(‘default’);}
Case 2:{ clg (‘case2’);}
Case 3:{ clg (‘case3’);}}
Default can be write anywhere inside the switch, we can have only one default in switch.
Break: it is a control transfer statement, it can be used in switch and loops block.

Loops: it is also called as iteration, the process of executing either a single statements or a block of statements repeatedly
multiple times is known as looping , block of statements executed repeatedly
1. While

19
2. do while
3. for
for in and for-off in arrays

while:
syntax:
while(condition)
{
Stmnts to be repeated;
}

Do-while:
Syntax:
do{
Stmt}
While (condition);

For loop: Syntax: (Initialization, condition, updation)

 for in: for index values


 for of : is for only values
 for each : here can access both index and value

let arr=[100,"hello",123,"abc123",true]
console.log((arr));
console.log(typeof arr);

//for in
for(let i in arr){
console.log(i);
}

//for of
for( let key of arr){
console.log(key);
}

//for each
arr.forEach((value,index)=>{
console.log(value);
console.log(index);
})
for loop forEach forof forin
Does not work with object Does not work with object, Does not work with object Works with object and arrays
only use with arrays
Does not ignore empty Ignores empty elements Does not ignore empty Ignores empty elements
elements elements

20
Break statement is Break statements is not Break statements is Break statements is
supported supported becauseit is a supported supported
method
Ignores extra properties Ignores extra properties Ignores extra properties Does not ignore extra
which does not have index which does not have index which does not have index properties which does not
have index
Performance 3 Performance 4 Performance 1 Performance 2

Function:
 It is block of code which is used to perform specific task.
 Functions will be executed only when it is called.
 The main advantage of function is code reusability.
 We call function ‘n’ number of times.
 In JavaScript every function is object.
Syntax:
Function identifier (parameter 1, parameterc2)
{
Statements / code;
}

function identifier (list of parameter,.........){


statements;
}

There are 2 ways to create function:


1. Function declaration statement or function statement
2. Using function expressions
Identifier is a variable it holds the reference of the function object
Note :
When we write to Console.log of function name, the entire function will be printed.
Variables or parameters:
The variables declare in the function definition is known as parameters
These parameters having local scope.(it is used inside a function.)
Parameters it will hold the address of the values passed by calling function.
Argument:
 These are values passed in the method called statements. This is called arguments.
 It can be a value or expression. (literals or values)

Parameter : the variables which is declared inside the function definition.


Parameter has scope of
Eg:Function sun (a,b)
Argument: the values passed in method while we are calling like string methods, array methods
Argument can be a literal( literal means value), or variable , or expression
Sum (10,20)
21
Sum(-10+3,20) ///expression
Let a=10; b=20; sum(a,b);

Return ():
Function expression:
1. a=> variable
2. a+b =>expression
3. 10 =>value

Only by using the object we can alter const value.

Syntax: var/let/const identifier = function(){}


Here the function is used as value

Disadvantage of function expression :


 We cannot use a function without declaration.
 Hoisting not possible in function expression.

We can create function using two types as


a. Function definition
b. Function expression

This:
 it is keyword it can be used as variable
 it will holds the address of global window object
 In JS every function will have this keyword.
 It is property of a function
 It is used to access the members (variables) of global execution context.

Constructor:
1. Name of the function should be in upper camel case
2. Parameters are treated as keys
3. Arguments that are values
4. Copy the values into the keys of the object from parameter using this keyword
5. To create object using constructor function new keyword
6. new create the object and its reference
function student(sid,sname) {
this.sid=sid;
this.sname=sname;
}
let s1=new student(1,'a');
let s2=new student(2,'b');
let s3=new student(3,'c');

22
console.log(s1.sid);
console.log(s2.sname);
console.log(s3.sid);
Construction function helps us to create multiple objects of ame type
1. Freeze method:
Freezes the object and does not let you make any changes
//freeze method
Var obj1={
ename:’sam’,
age:26,
place:’Mysore’
}
Console.log(object.freeze(obj1);
Obj1.age=27;
Obj1.place=’Bangalore’;
Console.log(obj1.age);
2. Assign method:
Object which will be modified using source object
var target={a:1,b:2, c:3,d:4};
var source={a:2,b:3,c:4};
console.log(Object.assign(target,source));

3.Entries:
let student={
sname:"dinga",
sid:1234,
}
console.log(student);
console.log(Object.keys(student));
console.log(Object.values(student));
console.log(Object.entries(student));

Functions in JavaScript:
1. Named Functions ( Legacy / Traditional way )
2. Function declaration statement
3. Function expression
4. Nested function **
5. Anonymous Function
6. Arrow function
7. IIFE(immediate invoking Function-call Expression)
8. Higher order function
9. Callback function
10. Constructor Function

23
Note: Inside a function we can always use the member of Global scope.

var city="Bangaluru";
function disp(name)
{
console.log('${name} is from S{city}');
disp('sheela');
} // sheela is from Bangaluru
 In the above example the variable name has local scope, and variable city has global scope
 Inside a function we can use both global and local variables.
this:
 this is a keyword used as a variable.
 It holds the address of global window object.
 Therefore with the help of this variable we can use members of global window object.

 var b=30;
 function disp()
{
 var b=10;
 console.log(b);//10 // local variable
 console.log(this.b);//30 it helps to get global variable
}
 disp();

1. Named Functions :
Lagacy / Traditional way
function myFunction () {
console.log("Coding");

}
myFunction ();

//Coding

2. Function expression:
 Passing a function for a variable as a value.
 Function expression cannot be hoisted.
 var a = function disp()
{
 console.log("hello");
}
 a(); //hello

here, variable ‘a’ changed as function a().


console.log(typeof a); //function

3. Anonymous Function: function without a function name , used as function expression or a arguments,
Function (){
//stmnts//function body

let greet = function (name) {


console.log (`Hello ${name}`);

24
};
greet ("SJS");
//Hello SJS

//example1:
var sqrt =function (x)
{
return x*x
}
console.log(sqrt(2)); //4

//example2:
var sum= function()
{
let a=10;let b=20; return a+b;}console.log(sun());//30

}
4. Arrow function:=>
It was introduced in ECMA script version6 (ES6).
It is used to reduce the lines of code in a function.
Syntax: (p1,p2…) =>{E}
Keyword identifier=()=>{
Stmnts;
}
Identifier()

Note:
 In arrow function parameters are optional
 If function has only one statement, then block is optional
 It is mandatory to create a block if return keyword is used.
 Shorter Syntax and one- lined functions
arrow function example:
//ARROW FUNCTION

2.
let greet = () => console.log (“Hello”);
greet();

//Hello
----------------------------------------------------------------------------------------
2.
const sum=()=>{
let a=10
let b=20;
return a+b;
}
console.log(sum());//30
---------------------------------------------------------------------------------------

EXAMPLE 3:
25
let a=10;
let b=20;
const sum=()=>{return a+b}
console.log(sum());//30

5. Immediately invoked Function Expressions (IIFE):


 When a function is called immediately, as soon as the function object is created it is known as immediate innovation.
 It is used for one time
 Executed immediately after their creation, used to create private scopes and avoid polluting the global namesspace.
Note: Steps to create immediate invoke function:
1. Treat a function like a expression by declaring inside a pair of brackets.
2. Add another pair of brackets next to it which behalf like function call statement.
3. Syntax:
Function functionname(){
Stmnts;
}

1.
(function demo(){
console.log("hello")
})();

2.
( function () {

let str = “ Good Morning”;


console.log(str);
}) ();

// Good Morning (Immediate Invoked)


BY using ARROW
let r= (()=> {
console.log("hello");
})();

6. Higher order function:


Function which accepts another function as parameter or return value. It should have minimum two function.
1. A function which returns another function is known as higher order function
2. A function which take another function as argument is known as higher order function.
(Or)
Functions that take one or more functions as arguments or return a function
Function operation (a, b, task)
Let res = task(a, b)
Return res;
Let sum= operation(10.5,function a, b){
Return a+b;})
Clog(sum);
Here, operation name is function name and a, b, task are parameter

26
Eg: map(), filter(), reduce()
let ary = [10, 20, 23];
let newAry = ary.map((element) => element + 10);
console.log(newAry);

//[20, 30.33]

//FILTER
let arr1=[10,20,40,60,,23,54,80]
let greater = arr1.filter((arr1)=> {return arr1>30})
console.log(greater); // used to filter the values in arrays

/MAP
let arr2=[2,3,4,5,6,7,8]
let greater2 = arr2.map((arr2)=> {return arr2*2})
console.log(greater2); // map is used used to modify the values in arrays and here we can add the value too
//reduce
let x=[1,2,3,4,5]
let r=x.reduce(function(acc,value){
return acc+value; //default value is 0 for addition
//return acc*value;//default value is 1 for multiplication
//1+0=>1
//1+2=>3
//3+3=>6
//6+4=>10
//10+5=>15
})
console.log(r);
here, //acc means accumlater it is a parameter, it acts as container

7. Callback Function:
Function that is passed as argument inside the another function is called a callback.
The function which rest

}outer();

8. Constructor Function :
Used as blueprints for creating objects with similar properties and methods. They are invoked using the new keyword to
create instances of objects.
function Person (name, place) {
this.name = name;
this.place = place;
}
let user1 =new Person (" Coding", "India");
console.log(`Hello everyone this is ${user1.name},and i am from ${user1.place}`);

//Hello everyone this is Coding, and i am from India

Scopes: visibility of a member to access it


Breakpoint: it will give the execution
Inside the function it is local scope
27
Local Scope:
 variable inside the function then it is local scope. We can use global variables inside local scope also
 The scope within the function block is known as local scope
 Any member with local scope cannot be used outside the function block

Script Scope: if it is const, let and it is outside the function then it is script scope.
Global scope: variable outside the function then it is global scope, only it is var keyword.
Inside function body we call access both local and global scope.
Using const we can change or using the value in object
TDZ: time taken between the variable declaring or creating and initializing variables is known as temporal dead zone.
let b; declaring
// console.log(b);
// b=20; intialize

Scope a chaining or Lexical Scope:


In a nested function, JS Engine search for a variable in the outer scope when it is not available in the local scope is known as
scope a chaining.
if variable is not available, it will be search outside function or block or outer scope, so ability to access the variable from
outside the scope
The scope chain is generally established between a child function and parent function with the help of closure
var a=10;
function x() {
var b=20;
function y() {
console.log(b);//20
console.log(a);//

}y();
}x();

Sources: development area


Steps: sources-> snippets-> create closure->if in scope area if I didn’t get anything means, please place a debugger
Closure:
 it is a process of binding parent function variables with child function.
 It enables JavaScript programmer to use parent function variable member inside child function.
 With the help of closure we can achieve lexical scope.
 Each and every time when, function is called closure will be creating.
Closure: it is a binding of parent functions variables with the child functions is known as closure
*What is the drawback in closure?
Memory wasted. Because high memory consumption

28
Stack: it is a block of memory, were object will be stored.
Stack will follows last in first out (LIFO) or first in last out (FILO).
Call stack: the stack is a organized block of memory where multiple objects can be stored, it follows a one stack, either it
follows FILO or LIFO. Call Stack is also called main or execution stack.
It is used for execution for execution of instruction in JS,
So JS is synchronous.
At any time only one instruction can be executed in JS, it not possible to execute more than one instruction in JS.
Stack Execution:
function one(){
two();
}
function two(){
three();
}
function three (){
console.log("hello");
return "end"
}
one();

29
Object Oriented Programming:
Object is a real time entity, which is having state and behavior
Example :
Car: properties
Color, price, model
Actions:
Drive, brake and moving
Webpage:
Properties: URL, content
Actions: Click, scroll
In programming world an object is a block of memory which represents a real world object, the properties of real world
object are represented using variables
We can create object in three ways:
 By Literals (values)
 const emp={
 // ename:"allen",
 // sal:2000,
 // job:"manager"
 // }
 // console.log (emp);

 // console.log(typeof emp);

 Functions
 function obj(eid,name, sal){
 // this.eid=eid;
 // this.name=name;
 // this.sal=sal;
 // }
 // let obj1= new obj(10, "smith",12312)
 // console.log(obj1)

 New keyword
 const student=new Object();
 student.name="millen";
 student.percentage="90";
 student.branch="CSE";
 console.log(student);

Object:
Real world or block of memory or attributes and behaviour

Properties of webpage

30
properties: content, bgcolor, url
actions: click, scroll, hover, focus
collection of attributes and actions in the form of key and value pair.
Key is property or attribute of an object
Value is state of an object
In JS there are 3 ways to create a object:
1) Object literals
2) Using function
3) Using class

1)obj literal
Let/const/var
Variables={}

Let/const/var identifier =
{ key1:value1,
Key2:value2,
.
.
.}
Ex: const emp1={
Ename:”dinga”,
Eid=123
}
Date Object and maths object:
Date object:

var date = new Date();


console.log(date);//using new operator will get current date,data getting from browser.

console.log(date.getDate());
console.log(date.getDay());//3
console.log(date.getMonth());//6 (month statrts from 0)
console.log(date.getHours());
console.log(date.getTime());
console.log(date.getMinutes());
console.log(date.getSeconds());
console.log(date.getMilliseconds());
console.log(date.getFullYear());//2022

///math object:
console.log(Math.sqrt(4));//2
console.log(Math.sqrt(36));//6
console.log(Math.cbrt(8));
console.log(Math.pow(2,3));///2power3(2*2*2)
console.log(Math.floor(4.9));///4
console.log(Math.ceil(4.9));//5
console.log(Math.max(4,5));//5
console.log(Math.random(4));//it create a random and return as floating point numbers in between range from 0 to 1.

To delete a object:
We can remove a key from an object with the help of delete operator y
Syntax: delete object_ref.key

31
Ex: const emp1-= {eid:1, ename:”alex”, sal:2000};
Delete emp1.sal;
Console.log(emp1);

Destructuring of Object:
The process of extracting the values from the object into the variables is known as Destructuring of object
Let/var/const { keyname, key_name,…} = obj_ref;
 All the key names provided on the LHS are considered as variables
 JS will search for the key inside the object into the variables
Ex: const emp { eid:1, ename:”vikas”,sal:5000};
Destructring : cons temp=(
eid:1,
ename:”vinay”,
sal:8000};
let{eid, ename}=emp;
consolelog(eid);
console.log(ename);

Rest parameter- spread operator: both rest and spread are introduced in ES6
 Rest parameter is used to accept multiple values as an array of elements, it convert multiple values into an array
 Rest parameter can be used in function definition, parameter list, to accept multiple value.
 It can also be used in array and object destructuring
 We cannot give default value to the parameter.Ffor
Rest parameter: Syntax […identifier]
Syntax
{variable1, variable2, ……….identifier}=object ref rest par in object

//Design a fuction which can accept multiple arguments and list them on the console:
Function test (b=5,…a){
Console.log(b)
Console.log(a.forEach(v=>console.log(v)));
}
Test();
Test(0,20,30,40,50,60,70)

Using parameter for destructuring:


Rest parameter can be used to detructure a JS object
Syntax:{variable1, variable2, ……….identifier}=object ref rest par. in object
Whne rest parameter is used for destructuring of object, all the key value pairs which is not yet extracted will be
destructured as an object.
Ex:
Const emp = { eid=;, name:”sham”,sal:8000,cno:101,};
Let ( eid, …remaining } =emp;

Array destructuring:
 Using rest parameter in array destructuring
 For rest parameter is used in array destructuring, then all the elements which isnot destructured will be copied into a new
array object and that array object will be returned
 Assigning the values to the variable, it helps to extract multiple values or property in an array -->
let a,b,rest;
[a,b]=[10,20];
console.log(a);
console.log(b);
[a.b,...rest]=[10,20,30,40,50]
console.log(rest);

32
Using rest parameter to clone array or object :
let arr=[10,20,30,40,50]
console.log(arr);
let c=arr;//reference array, here c is refernce and holds ooriiginal array
console.log(c);

let[...d]=arr;
console.log(arr);//cloning of array
console.log(arr===c);//true, reference array
console.log(arr===d);//false, it is not a original array. here, cloning
arr[arr.length]=70;
console.log(c);//[10,20,30,40,50,70]
console.log(d);//[10,20,30,40,50]

Object Clone: To clone a object


Syntax:
Let {…identifier}= obj-ref
const emp={
eid:123,
ename:"dinga",
}

let e=emp;//ref copy


let{...e2}=emp;//cloneing of object
console.log(emp);
console.log(e);
console.log(e2);
console.log(emp===e);//ref
console.log(emp===e2);//clone
emp.cno=101;
console.log(e);
console.log(e2);

Spread Operator:
It is used to perform unpacking, spread operator uses an iterator to access each and every element or a property present in
the array or object
let student ={
sname:"krishna",
sal:2000,
id:1234
}
console.log(student);
// console.log(...student);

let city ="bangaluru";


console.log(city);
console.log(...city);

let name="krishna";
console.log(...name);//iterator error or type error none callable iterator

let city1="mysuru";
console.log(...city1);
let arr=[...city1];
console.log(arr);

33
let obj={...city1};
console.log(obj);

Prototype:
function has a attributes r properties, holds the address of the reference of the object. It array like object.
it is an object created for every constructor function.
Note: when an object is created using a literal then the object proto(obj__proto__) refers to prototype of obj.
function emp(eid,name)
{
this.eid=eid,
this.name=name,
}
When the instaence of emp is created. ox3
Let e1 = new emp(1,’A’); work
Let e1 = new emp(2,’B’);

emp Ox1 f

ox2 prototype
prototype work ox3

e1
eid 1
ox11
name A
proto
Ox2

e2 eid 2
Ox12 name B
proto
Ox2

to add a number into emp.Prototype


member into emp.Prototype
Emp.prototype.work=()=>console.log(“work”);

Advantage of adding a member in a prototype


We can access reference of any object which belongs to that prototype

//to update using prototype for keys and value pair


let obj={
sname:"suresh",
sid:1234,
sbranch:"CSE"
}
console.log(obj);
console.log(obj,ssal=1000);
console.log(obj);
console.log(obj.__proto__.ssal=1000);

//Design a JS function which can accept an array log the elements in reverse order.

34
let a=[1,20,30,40,50];
console.log(a.reverse(a));
or
//using prototype
Array.prototype.rev=(a)=>{
console.log(a.reverse(a));

}
console.log(a.reverse(a));

Arrays:
In arrays we can store multiple values, in a single variable instead of storing in multiple variables.
In JavaScript Arrays is Heterogonous
Methods of Arrays:
1. To check Array length :To check length of the array
console.log("length of array is",hobbies.length);

2. Push: In array adding a element/ elements in the last index, It will add the elements at the end of array
//push
let arr1=[11,22,33,44]
arr1.push(6,7,8) //it will add the elements in the array at the end
console.log(arr1);

hobbies.push("swimming")
console.log("after push", hobbies);

3. Pop: To remove the elements from the last index:


let arr2=[1,2,3,4,5,6]
arr2.pop() //it will remove the element from the end but only one element //it does not except arguments
console.log(arr2);

hobbies.pop();
console.log("after pop", hobbies);

4. Unshift: To add element to first index


let arr4=[12,13,14,15]
arr4.unshift(100,200) //it will add the element in the beginning
console.log(arr4);

hobbies.unshift("sleeping");
console.log("after unshift",hobbbies);

5. shift: To remove the element from first index

6. //shift
35
7. let arr3=[111,222,333,444,555]
8. arr3.shift() //remove element at the beginning
9. console.log(arr3);

hobbies.shift();
console.log("after shift",hobbbies);

6. Indexof:
index of
let arr5=[1,2,3,45]
// a.indexOf(1) //not give any input
console.log(arr5.indexOf(1));

7. Includesof:
includesof

let arr7=[1,2,3,4,5]
console.log(arr7.includes(1));

For in:index
For of:value
var arr=[10,20,30,40,50]
for ( var ele in arr) {
console.log(arr);
}

For each: both index and value


var arr=[100,200,300,400,500]
arr.forEach(myfunction)

function myfunction(values,index)
{
console.log(values,index);
}

100 0
arrays.js:72 200 1
arrays.js:72 300 2
arrays.js:72 400 3
arrays.js:72 500 4

Document Object Model (DOM):


Document is an object created by browser
The document object is the root node of DOM tree.
DOM:
1. The every html element is considered as a none ( JS object) in DOM.
2. DOM allows to modify the document content rendered by the browser without reloading the page. Therefore DOM helps
to make a web page dynamic.

36
NOTE: 1.ANY modification done using DOM is not updated to the original page. Therefore, once we reload a page all the
modification done using DOM will be lost.
2. We can write the content on the browsers dynamically with the help of write and writeln method of document object.
Ex: To display a message on the browser page from JavaScript code:
document.write(“Hi”);
-DOM is not JavaScript, it is built using JS
-DOM is a object oriented representation of html file.
- Every time an html document is given to the browser, it automatically generated it can be accessed and modified using the
root node document in JavaScript.

Methods in DOM:
1. getElementById() :
for this method weneed to pass the ID of an element as a String, it returns the first element specified ID.
Syntax:
Document.write.getElementById(“ID”);

2. To fetch an element from DOM using the class name: getElementsByClassName();


pass the class name as String
it returns a nodelist, containing all the elements matching the given html collections, which is similar to array but not an
array.
Syntax: document.getElementsByClassName(“class”);
Let e3= document.getElementsByClassName(“divstyle1”)
Console.log (e3);

3. to fetch the elements from the DOM using tag name: getElementsByTagName();
4. We need to pass tag name as a string.
5. It returns as html collection containing all the elements matching the given tag name.

Tag: predefined word present in html.


To fetch the elements from the DOM using CSS selectors:

37
We can select an element from DOM using CSS selectors with the help of
1. querySelector
2. querySelectorAll

Note:
 We need to pass a CSS selector as a string.
 Query selectors returns the reference of first element found.
 QuerySelectorAll returns a node-list of all the elements found in the original order.

Event:
FILTER used to filter the values in arrays
let arr1=[10,20,40,60,,23,54,80]
// let greater = arr1.filter((arr1)=> {return arr1>30})
// console.log(greater);

Map: map is used to modify the values in arrays and here we can add the value too
let arr2=[2,3,4,5,6,7,8]
let greater2 = arr2.map((arr2)=> {return arr2*2})
console.log(greater2);

Event:
An action performed by the user on the webpage is known as a event
End user can perform different types of events such as mouse events, keyboard events etc.,
We can dynamically add events to a DOM tree without adding it in the HTML file
There are two ways: JS and Jquery
Eventlistener/ Event handler
1. Capture the event
2. Target element – execute
3. Bubble
Event Propagation:
1. capture
2. Target
3. bubble

 Event Listener: it is a function which executes a task when an event is occurred on the Most specific element.
 Event flows like event bubbling and event capturing.
 Event bubbling: it is the event starts at the target element (most specific element) and then flows in theupward direction
of the DOM tree
 Event capturing: an event starts from the top of the DOM tree (least specified element) and flows downwards up to the
target element
 Parent of docuent in browser is window
Event Object:
Every event is an object
An object which is created for an event when an event occurs.
Web browser creates the event object when the event occurs
Important methods: Type, Target, bubbling, current target, Stoppropagation

38
Types of Events:
1. User interface events
2. Focus and blur events
3. Mouse events
4. Keyboard events
5. Form events
6. Mutation evnets and observers
7. HTML5 events
8. CSS events

BOM: Browser object Model it is action performed like navigator, Screen, timer, linking one page to another, location of the
page

Asynchronous: The behavior of making way for others


We can achieve asynchronous behavior with the help of setTimeOut() method
setTimeOut():
it is method of window object
it accepts two arguments :1 a callback function, 2. Delay time in miliseconds

//Synchronous
function print(m,n){
for (let i=m;i<n;i++)
{
console.log(i);
}
}
function msg(){
console.log("msg function executed")
}

print(10,4000)
msg();

//**making JS as Asychrnous using setTimeout():

function print(m,n){

setTimeout(() => {

39
for (let i=m;i<n;i++)
{
console.log(i);
}
},4000);//4 seconds(4000 mili-seconds)
}
function msg(){
console.log("msg function executed")
}
print(10,40)
msg();

Promise:
Promise are a powerful feature introduced in ES6 to handle asynchronous operations in a more organized and readable
way.
Promises represents a value that may not be available yet, but will be resolved or rejected in the future.
The Promise is an object in Javascript that is use for asynchronous programming.
In promise object there are two methods:
a. Then(cb) it can accept a call back a function. The callback function passed to then method gets executed only when the
promise returns resolve.
b. Catch(cb): it can accept a call back function. The call back function passed to catch method gets executed only when the
promise returns reject.
Creating a Promise:
To create a promise, you use the Promise constructor, which takes a function as an argument.
This function, called the “executor”, receives two parameters: resolve and reject. Inside the executor function, you perform
the asynchronous operation and call resolve (value)when it succeeds or reject (error)when it fails.
const myPromise = new Promise((resolve, reject) => {
// Asychronous or time-consuming operation here
// You can use resolve(value) to fulfil the promise with a value.
// You can use reject(error) to reject the promise with an error.

});
Return go(f, seed, [])
}

Example to creating a promise:


const fetchData = (url) => {
return new Promise ((resolve, reject) => {
//Simulate an asynchronouw operation( e.g., fetching data from a server)
setTimeout(() => {
const data = { id :1, name:'Davd Steve'};
if (data){
resolve(data);//Resolve with the fetched data
}})
} else {
reject (new Error ('Data not found'));//Reject if data is not available

}
},2000);//Simulate 2 seconds delay
});

40
};
In the above example the fetchData function returns a Promise that simulates an asynchronous operation by fetching data
from a server. After a 2 second delay, it resolves with an object containing id and name, or rejects with an error message
“ Data not found” if the data is unavailable.
Handling Promise Result:
Promises allow you to handle the resolved or rejected value using the .then() and catch() methods, respectively. You can
chain multiple .then() methods to perform sequential operations.
Syntax:
myPromise

.then((result) => {
//code to handle the fulfilled result goes here
console.log("Promise fulfilled with:",result);
})
.catch((error)=>{
//code to handle the rejected result goes here
console.error("Promise rejected 2ith error:", error.message);
});

Example

fetchData('https://api.example.com/data')
.then((data)=>{
console.log('Data fetched:', data);
return data.id;
})
.then((id)=>{
console.log('ID:',id);
})
.catch((error)=>{
console.error('Error:', error.message);
});

Demonstration of Promise work:

Promise

.catch .then

Error Async
Handling Action

Example:1
const myPromise = new Promise((resolve, reject)=> {//Makes the function
setTimeout(()=>{//Javascript native function
resolve("call") // calls this function when the time is completed
},300)

})

41
Example:2
const myPromise = new Promise((resolve, reject) => {
if(/*condition */){
resolve();
}
else{
reject();
}
});
myPromise.then(res =>{
/* handle resolve */
}).catch({
/* handle reject */
})

Promise states:
1. Pending: A Promise is in process, The initial state is when a promise is created and not yet resolved or rejected.
2. Fulfilled-A promise has been completed, the stste when the promise is successfully resolved with a value.
3. Rejected- A promise has been failed, The state when the promise encounters an error or is explicitly rejected.
Examples of Promise states:
1. const pendingPromise= new Promise((resolve,reject) => {

// This promise is in the pending state as it has bot been resolve or rejected yet.
//You can perform asynchronous operations here and thebresolve or reject the promise accordingly.
});

2. Fulfilled Promise:

const fulfilledPromise=new Promise((resolve,reject)=>{


//this promse is immediately fulfilled with a value (in this case, the value is 42),
resolve(42);
});
fulfilledPromise.then((result)=> {
console.log("Fulfilled with value : ", result);//output: Fulfilled with value:42
});

3.Rejected Promise:
const rejectedPromise=new Promise((resolve,reject)=>{
//this promise is explicitly rejected with an error message.
rejectdPromise.catch(error)=>{
console.error("Rejected with error:", error.message);//output:Rejected witherror : Soething went wrong!

});

Methods in promises:
1. .Promise .all():
This method takes an array of promises and returns a new promise that resolves when all the promises in the array are
resolved. The resolved value is an array containing the resolved values of all promises.
2. Promise.race():
This method takes an array of promises and returns a new promise that resolves or rejects as soon as any promise in the
array resolves or rejects. The resolved value will be the value of the first resolved promise.

onst promise1 = fetchData ('https://api.example.com/data/1');


const promise2 = fetchData ('https://api.example.com/data/2');
Promise.all([promise1,promise2])
.then((results)=>{
console.log('All data fetched:', results);

42
})
.catch((error)=>{
console.error('Error:', error.message);
});
Promise.race([promise1,promise2])
.then((results)=>{
console.log('First data fetched:', result);
})
.catch((error)=>{
console.error('Error:', error.message);
});

The code fetches data from two different URLs using promises. The Promise.all() method waits for both promises to resolve
and logs all the fetched data to the console. The Promise.race() method waits for the first promise to resolve (or reject)
and logs the data from the first resolved promises to the console. If there is an error in any of the promises, the error
message is logged to the console.
Promise v/s Async Await
 Promise vs Async Await is a whole topic itself but one of the major difference is Promise use nested functions (.then) which
eventually makes too many nested functions and code looks like a mess.
 On the other hand Async Await keeps the code look more synchronous and clean.
 At the end, both helps you achieving the same task.

Promise.all()and Promise.allSettled() are both methods used to work with multiple promises in JavaScript, but they have
different behaviors and use cases.
Choose Promise.all() when you need all promises to fulfill successfully and want their combined results. Use
Promise.allSettled() when you need to handle all promise outcomes, including both fulfilled and rejected promises.

Fulfillement vs Settled Status:


Promise.all() waits for all the promises to fulfill (successfully complete) or reject (encounter an error) and either returns an
array of fulfillment values or rejects with the reason of the first rejected promise.

Promise.allSettled(): waits for all the promises to either fulfill or reject, and it always return an array of objects, each
representing the outcome of an individual promise, whether it fulfilled or rejected.

const promise1 = Promise.resolve('Promise 1');


const promise2 = Promise.reject('Promise 2');
const promise3 = Promise.resolve('Promise 3');

Promise.all([promise1, promise2, promise3])//using promise .all()


.then(results => console.log(results))
.catch(error => console.error(error));

Promise.allSettled([promise1, promise2, promise3])//using promise .allsettled()


.then(results => console.log(results));
OUTPUT
//[object object]
[{
"status": "fulfilled",
"value":"Promise 1"
},
{
"status": "rejected",
"value":"Promise 2"
},
{
"status": "fulfilled",
"value":"Promise 3"
}]

Handling Rejections: In Promise.all(), if any of the promises reject, the whole promise chain immediately rejects with the
reason of the first rejected promise, and the remaining promises’ results are not accessible.

43
In Promise.allSettled(), even if some promises reject, the resulting array will contain information about all the promises,
including both fulfilled and rejected ones.
Use: where you want to process the outcomes of all promises, regardless of whether they succeeded or failed.

<script>
const promise1 = Promise.resolve('Promise 1');
const promise2 = Promise.reject('Promise 2');
const promise3 = Promise.resolve('Promise 3');

Promise.all([promise1, promise2, promise3])//using promise .all()


.then(results => console.log(results))
.catch(error => console.error(error));

Promise.allSettled([promise1, promise2, promise3])//using promise .allsettled()


.then(results => {
results.forEach(result =>{
if(result.status === 'fulfilled'){
console.log(result.value);
} else if (result.status === 'rejected') {
console.error(result.reason);
}
});
});

//
// "Promise 1"
// "Promise 2"
// "Promise 3"
// "Promise 2"
//

Handling Mixed results: Promise.all() works well when you are interested in the combined results of multiple promises and
can tolerate the failure of the entire operation if any promise is rejected.
Promise.allSettled(): is useful when you want to ensure that all promises are given a chance to complete and you need to
process the results of all promises, regardless of whether they succeeded or failed.
Race method: it depends on timings, if we want use time means we can use set-timeout.

Questions:
 Why JS called as dynamic and loosely typed language.
 List the JS keyword
 difference b/w dynamic and static
 null data type will accepts space or not
 dynamically typed
 write a JS code to store your following details:
 name, age, gender, degree, aggregate and display all these on console.
 Read the text from the browser using the prompt and display the number of characters present in the text.
44
 Read first and last name from the browser using the prompt and display full name on the console
 Read the age of a person by using prompt , if the age is greater than 18 console a message as “ the person is adult” or
console a message as “ the person is minor”
 What is String and String object
 IndexOf will accept two argument define why with example
 Write a JS code to achieve the following requirement: Assume We have a container which keeps the count of items, if
count is zero display message empty if the count is non zero display the count.
 Write JS code to read the source, location, distance between source and destination from the browser prompt assuming
the cost per km is 8.5 display the approx. cost the user has to pay to reach the destination from source on the console.
 Read the name of the city from the user using prompt, Read a single digit lucky number from user display the character
present in the index position
 Write a JS code to read the two number from prompt and find the largest number
 Write a JS program to read the age of a user from the prompt and display message in the console, whether the user is
eligible to access adult content or not.
 Write a program to accept total number of products bought and the total cost from the prompt and display cost of one
product on the console.
 Write a JS Program to read a name of the person using prompt and display whether the person name is of even length or
odd length. (Hint: use ternary)

 Write a program to read a name of the fruit from the prompt, read a character from a user from the prompt check
whether the character is present in the fruit name or not, and print suitable message on the console. (Hint: use ternary)
 Write a JS code to read the four number using the prompt, and log minimum number in the console.
 Write a JS code such that when a user enters any other number between 1 and 7 name of te weekday must be displayed
Sunday starts from1, if the users enters any other number an invalid message to be displayed. Like, Sunday-1 Monday-2,
Tuesday-3, Wednesday-4, Thursday-5, Friday-6, Saturday-7 8-invalid message should be console.
 Read the marks in prompt, if the if marks is more than (>90<80) marks >90 distinction, else if(>90<80) marks>80 first
class, else if (>90<80) marks>60 second class. Else console( fail). It can be done by using both switch case and switch case.
 Write a JS code to display number 1-5 using while loop
 Write a JS code to display number 1-5 using do-while loop
 Write a JS code to display the text five times using for loop
 Write a JS code to find the sum of positive numbers using both while and do while. If user enter the negative number
means it should execute.
 Write a JS code to find the factorial of n numbers using for loop.
 Function: Design a function which can accept radius of circle and prints the diameter on the console
 Write a function which can accept the centimetre and print the data in the meter using a function.
 Design a function which can accept a number and returns its square

 What is the difference between function statement and function expression, explain with an example.
 What are the advantages of function in JS.
 Difference between slice and splice
 Design a function to add 3 to all the element and display the new array. Let arr=[10,20,30](using one method)
 Design a function to add 5 and find the even numbers from the addition and display. (use filter and other method) let
arr=[]
 Create an object , object name: ”marker”, with following attributes:
 1.ink, brand,price
o create a object
o display object
o log the price
o color=blue,black (should be done both in dot and bracket notation.
 and add one key value pair, shape:cylinder, display entire object

 Create an object with the following details:


 Kart{pname, (atlest add 4 product)
 Price;}
45
o atleast add 4 object,
o Find total cost of the kart
o what will be the price of the product if there is an 5% discount for every element
o display names of the product whose length is even.

 Design a JS function which can accept an array log the elements in reverse order.

46

You might also like