JS Notes
JS Notes
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)
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.
Browser
Parser
Deployed on
Console (inspect)
AST: Abstract Syntax Tree and PARSER: Converts HTML code to AST
Browser – Parser—AST—Machine Level Language –Console
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>
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");
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
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
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
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);
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
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 %=
OR(||)
T T T
F T T
12
T F T
F F F
NOT(!)
T F
F T
Ex: console.log (!(a>b)
console.log (!(a<b)
TRUE FALSE
( Conditon ) ? Expression 1 : Expression 2
Operand 1 Operand 2 Operand 3
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.
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
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
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));
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
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);
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;
}
Return ():
Function expression:
1. a=> variable
2. a+b =>expression
3. 10 =>value
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
3. Anonymous Function: function without a function name , used as function expression or a arguments,
Function (){
//stmnts//function body
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
1.
(function demo(){
console.log("hello")
})();
2.
( function () {
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}`);
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
}y();
}x();
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:
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)
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]
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 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
//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);
hobbies.pop();
console.log("after pop", hobbies);
hobbies.unshift("sleeping");
console.log("after unshift",hobbbies);
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);
}
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
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”);
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.
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
//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();
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, [])
}
}
},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);
});
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:
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.
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.
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.
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 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
Design a JS function which can accept an array log the elements in reverse order.
46