JavaScript(JS)
What is javascript ?
JavaScript is a scripting language that enables you to create dynamically updating
content, control multimedia, animate images, and pretty much everything else.JavaScript, often abbreviated
as JS, is a programming language and core technology of the Web, alongside HTML and CSS. 99% of websites
use JavaScript on the client side for webpage behavior.Webbrowsers have a dedicated JavaScript engine
that executes the client code.
Data Types in JavaScript
Data Types in JavaScript
- String Type
- Number Type
- Boolean Type
- Null Type
- Undefined Type
- Object Type
- BigInt Type
- Symbol Type
Prototype
JavaScript is a prototype based language so whenever we create a function using javascript.
JS engine create a prototype property function.
Protoype property is basically an object where we can add methods and properties in it.
All javascript objects inherit properties and methods from a prototype.
Adding properties and methods to object using the prototype.
Protoype allow us to add new properties to object constructor.
let Mobile = function (brand, model) {
this.brand = brand;
this.model = mode;
this.price = 15000;
}
let samsung = new Mobile('Samsung', 'J7 Prime');
console.log(samsung);
let nokia new Mobile('Nokia', 'M128P');
nokia.color = 'blue'; // Added new properties but will not be available for other object
//Protoype is super class, parent class, base class known
//classname.prototype.key = 'value';
Mobile.prototype.color = 'green';
Closure
A closure is a function which can access the parent scope.It preserve the data from outside.
A closure is an inner function that can access the variables of outer function.
function outerFunc() {
var a = 20;
function innerFunc() {
console.log(a)
}
innerFunc();
}
outerFunc();
-
Advantages:
- Variables in closure can help us to maintain state that we can use later.
- It provide data encapsulation.
- It help remove redundant code.
- It help maintain madular code.
- Disadvantages:
- The varaiables declared inside closuer which are not garbage collected.
- Too many closures can make slow down application.This actually caused by duplication of code in the
memory.
Callback
A callback function is a function,It can be any function anonymouse function, arrow
function passed into another function as an argument which is invoked inside the outer function to
complete some kind os action.
// Example
function show(val) {
console.log(val)
}
function demo(callback) {
var a = 20;
callback(20);
}
demo(show);
Call Method
The call method is a predefined JavaScript method by using call method an object can use
a method which belong to another object take argument separately.
let user1 = {
name: 'Saten',
city: 'Mumbai',
show: function (title) {
console.log(`myname is ${thi.sname} form ${this.city} ${title}`);
},
};
let user2 = {
name: 'anshum',
city: 'punjab',
};
user1.show.call(user2);
user1.show.call(user2, 'software engineer');
Apply Method
The Apply method is a predefined javascript method by using apply method an object can
use a method which belong to another object take second argument as an array.
//Example 1
let user1 = {
name: 'Saten',
city: 'Pune',
show: function (title, profession) {
console.log(
`myname is ${this.sname} form ${this.city} ${title} ${profession}`
);
},
};
let user2 = {
name: 'Nirupam',
city: 'Bengal',
};
user1.show.apply(user2, ['Mobile', 'UI/UX Designer']);
//Example 2
let arr = [0, 12, 4, 2, 18, 9, 2, 6, 10];
let result = Math.max.apply(this, arr);
console.log(result);
Bind Method
Bind method is predefined method in JavaScript by using this method we can bind an object
to a common function so that the function gives different result when it need the bind method to takas an
object as on first argument and creates a new function.
let user = {
name: 'Saten',
city: 'Pune',
contry: 'India',
show: function () {
consal.log(`my name is ${this.name} i live in ${this.city} form ${this.Country}`);
},
};
let newFunction = user.show.bind(user); // Correct
newFunction();
Shallow Copy
To copy object shallow copy create a new object with references to the same memory location as the
original object at first level of properties but not nested object .
//Example 2
let obj = {
name: 'saten',
city: 'Mumabi',
};
let user = Object.assign({}, obj);
//Example 2
let obj = {
name: 'saten',
city: 'Mumabi',
};
let uesr = { ...obj };
Deep Copy
Deep copy is to object deep copy object a new object with new memory locations for all its properties and
object or array.
let obj = {
name: 'saten ',
address: {
city: 'kanpur',
state: 'up',
showInfo: function () {
return 'This is object for clone';
},
},
};
// using json parse and stringify
let user = JSON.perse(JSON.stringify(obj));
// using loadash.js library
let user = _.cloneDeep(obj);
Higher Order Function (HOF)
A function which takes another function as an argument and returns a function is known as a higher order
function.Predefined Higher Order Function,Please check below.
- Map: is function of array object,It take an array and always return new array with
updated value and
results.
let arr = [1,2,3,4,5,6,7,8];
let newArr = arr.map((val) => {
return val
});
console.log(newArr);
- ForEach: is function of array object,It take an array but does not return anything and
only modify the original array.
let arr = [1,2,3,4,5,6,7,8];
let newArr = arr.forEach((val) => {
console.log(val)
return val //It will return undefined
});
console.log(newArr);//It will return undefined
- Filiter: function is to filter or find specific item or element in array and return new
array.
let arr = ['Ram','Sham','Sita','Hanuman','Valmiki'];
let newArr = arr.filter((name) => name === 'Ram' ? name : null);
console.log(newArr);
- Reduce : - is used to reduce the array to a single value and execute provided function
stored
in accumulator & Map.
let arr = [1,2,3,4,5,6,7,8];
let newArr = arr.reduce((ac, value) => {
return ac+value;
});
console.log(newArr);
//Map Higher Order Function
const arr = [8, 4, 6, 5, 3];
function double(x) {
return x * 2;
}
function triple(x) {
return x * 3;
}
function binary(x) {
return x.toString(2);
}
const result = arr.map(double);
const result = arr.map(triple);
const result = arr.map(binary);
// double = [16, 8, 12, 10, 6] ]
// triple = [24, 12, 18, 15, 9] ]
// binary = ['1000', '100', '110', '101', '11'] ]
//Higher Order Function
const arr = [3, 2, 1, 4, 5, 8];
const area = function(num) {
return Math.PI * num * num;
};
const circumference = function(num) {
return Math.PI * num * num;
};
const diameter = function(num) {
return 2 * num;
};
const calculate = function(arr, logic) {
const output = [];
for (let x = 0; x < len; x++) {
output.push(logic(arr[x]));
}
return output;
};
console.log(calculate(arr, area));
console.log(calculate(arr, circumference));
First Class
First class in javascript in programming language to have first class function so that can be assigned to
any other variable or passed as an argument or can be return by another function.
It can be stored as a value in a variable.
it can be returned by another function passed as a parameter into another.
Stored in an array,queue,stack its ow n methods s property.
Hoisting
Hoisting is javascript mechanism where variables and function declaration are moved to the top of their
scope before the code execution.
A variable con be used before it has been declared.
// Variable Hoisting
var a;
a=10 ;
//we write like this
var a = 10 ;
var a = 10 ;
document . write (a )
var b = 20 ;
// Compile phase
var a;
var b;
a=10;
document.write(a);
b=20;
// Function Hoisting
sum(4,5);
function sum(x,y){
add = x+y;
console.log(add);
}
sum(4,5) //This is not hoisting
Normal and Arrow Function
Normal Function
- Normal function arguments objects are available in normal function.
- Normal functions create using function declaration or expressions which are “constructible” and
callable.
// Function
function add (x ,y ) {
console.log (arguments) // arguments objects
retun x + y
}
// Contructible and callable function
function Car(name ) {
this.brand = name;
}
let carObj = new Car('Tata Innova');
console.log(carObj.brand);
Arrow Function
- Fat arrow function arguments objects are not available in arrow function.
- We con not create cons truncation in arrow function.
- Arrow function do not have their own this key.
- Implicitly returned by the arrow function.
// Implicitly returned by the arrow function.
const show = ( ) => 100;
Pure and Impure Function
Pure Function
Pure functions are the functions that accept an input and returns a value without
modifying any data
autside its scope (side effect).
Predecitable and without side effect
function add (x) {
return x+1;
}
add(10);
add(12);
Impure Function
An impure function is a function that contains one or more side effects. It changes the data outside
of its lexical scope and does not predictably.
var x = 10;
function add (x) {
console.log(x)
x++;
}
add(); // = 11
add(); // = 11
add(); // = 12
//Value are being changed on each call of method show different result
Function Expression
Function Expression
A function expression can be used as an IIFE (Immediately Invoked Function Expression)which runs as soon
as it is defined.
const sum = function (a, b) {
const total = a+b;
console.log(total);
}
sum(10, 12);
Return Statement
Return Statement
A return statement which may be return any type data, including array and objects
function show(a, b) {
const total = a+b;
return total;
}
show(12,5,) // return number data type
Lexical Scope
Lexical Scope
So whenever we create a function in javascript we are creating a scope, Which means variables inside
that method which are not accessible from outside.This means that the scope of a variable is determined
in the block of code. Block scope variables.
function show() {
const x = 10; // block scope variable
const y = 12; // block scope variable
return x+y;
}
show()
Debouncing and Throttling
Debouncing
Debouncing enforces that a function wont be called again and again until a certain amount of time has
passed without it being called.
Example: Searching in search box the function is being called to hit API to fetch data on each key press
because of this hit api everytime because of this the application get slow.
To stop this we use debouncing concept, a function will be called after few milli seconds.
let counter = 0;
function fetchData() {
console.log(`Fetching data ${counter}`);
}
function debounce(call, d) {
let timer;
return function(...args) {
if (timer) clearTimeout(timer);
setTimeout (() => {
call();
}, d)
}
}
const searchFunc = debunce(fetchData, 1000);
<input type="text" id="Search" onChange="searchFunc()" />
Throttling
Enforces a maximum number os times a function can be called over time.
What is Temporal Dead Zone?
Temporal dead zone is the period of the time during which the let and const declarations can not be
accessed.temporal deda zone start when the code execution enters the block which contains the let or const
declaration and continues until the declarations has executed.
Json Parse and Stringify?
JSON: Javascript Object Notation.
Json Parse
A common use of json is to exchange data to from a web server.It convert text into a javascript object
when recieving data from from a server.The data is always a string.
Date objects are not allowed in json.
const data = '{ "name": "Ram", "city": 'Ayodha UP' }';
const obj = JSON.parse(data);
console.log(obj.name, obj.city);
Json Stringify
It converts object into string when sending data to a web server the data has to be a string.
var obj = { "name":"Ram", "city":"Ayodha", "state":'UP'};
var jsonData = JSON.stringify(obj);
console.log(jsonData);
Global Execution
Global Execution
javascript engine creates the global execution centext before tit starts to
execute any code.
Variables and function that is not inside any function. A new execution
context
get created everytime a function is executed.
The global execution context just like any other execution context, except
that it
get created by deafult, it associated with global object, which means a window object.
Thread in JS
Thread in JS
A thread is a single sequential flow of control in a program. Sequence of execution of programmed
instructions.
JavaScript is a single thread-based language,Top to bottom flow.
JavaScript is an asynchronous programming language.
Thread of execution in JavaScript is synchronous by nature but also non-blocking like asynchronous.
Which means it moves to the next line only when the execution of the current line is completed.
Microtask in JS
Thread in JS
A microtask is a short function that is executed after the function or program is created. It exits and
only if the JavaScript execution stack is empty.
Example:
- Promise resolutions: then | catch | finally
- Mutations observers
- Other APIs like queueMicrotask()
They are executed before any macrotask or rendering activity.
Macrotask in JS
Macrotask in JS
Macrotask represents large tasks that can be split over multiple JavaScript engine ticks.
They are typically more complex operations that require more time to complete.
Example:
- setTimeout
- setInterval
- setImmediate (Node.js)
- Interaction events (click, keyboard events, etc.)
- The macrotask queue is sometimes called the task queue.
Event Loop
Event Loop
Event loop in javascript is a mechanism through which the calls waiting for execution in the callback
queue/job queue can be put on the call stack.
For any evet loop from the callbakc queue or job queue to come to call stack, The call stack will have
to be empty.
- Call stack : where we have global execution
- Event Loop: such as setTimeout function has callback (CB)
- Callback queue: It will keep in queue (CB)
- Execution stack in global execution context
Asynchronous & Synchronous
Asynchronous
Asynchronous functions running in parallel with other functions are called asynchronous.
Asynchronous code allows the program to be executed immediately where the synchronous code will block,
further execution of the remaining code until it finishes current one.
Synchronous
Synchronous means to be in a sequence, i.e every statement of the code gets executed one by one. So
basically a statement has to wait for earlier statement to get executed.