Javascript_new
Javascript_new
*************
Datatypes:-
var declarations are globally scoped or function scoped while let and const are block scoped.
var variables can be updated and re-declared within its scope; let variables can be updated but
not re-declared; const variables can neither be updated nor re-declared.
They are all hoisted to the top of their scope. But while var variables are initialized
with undefined, let and const variables are not initialized. however—let and const are hoisted
(like var, class and function), but there is a period between entering scope and being declared
where they cannot be accessed. This period is the temporal dead zone (TDZ).
A temporal dead zone (TDZ) is the area of a block where a variable is inaccessible until the
moment the computer completely initializes it with a value.
While var and let can be declared without being initialized, const must be initialized during
declaration.
While var declared binds to window object(only the variables present in the global scope), let
and const does not.
Reference:
https://www.freecodecamp.org/news/javascript-temporal-dead-zone-and-hoisting-explained/
https://dev.to/kozlovzxc/js-interview-in-2-minutes-var-let-const-39p1
Hoisting:-
Hoisting is JavaScript's default behavior of moving all declarations to the top of the current
scope (to the top of the current script or the current function).
JavaScript only hoists declarations, not initializations.
variables are hoisted
function declaration hoisted
function expression not hoisted
Reference:
https://www.freecodecamp.org/news/javascript-temporal-dead-zone-and-hoisting-explained/
Strict Mode:-
1
Strict mode eliminates some JavaScript silent errors by changing them to throw errors.
Strict mode fixes mistakes that make it difficult for JavaScript engines to perform optimizations:
strict mode code can sometimes be made to run faster than identical code that’s not strict
mode.
Strict mode prohibits some syntax likely to be defined in future versions of ECMAScript.
It prevents, or throws errors, when relatively “unsafe” actions are taken (such as gaining access
to the global object).
It disables features that are confusing or poorly thought out.
Strict mode makes it easier to write “secure” JavaScript.
Reference:
https://www.geeksforgeeks.org/strict-mode-javascript/
Call invokes the function and allows you to pass in arguments one by one.
func.call(obj, 'param1')
example:
var person1 = {firstName: ‘Jon’, lastName: ‘Kuperman’};
var person2 = {firstName: ‘Kelly’, lastName: ‘King’};
function say(greeting) {
console.log(greeting + ‘ ‘ + this.firstName + ‘ ‘ + this.lastName);
}
say.call(person1, ‘Hello’); // Hello Jon Kuperman
say.call(person2, ‘Hello’); // Hello Kelly King
Apply invokes the function and allows you to pass in arguments as an array.
func.apply(obj, [paramsArray])
example:
var person1 = {firstName: ‘Jon’, lastName: ‘Kuperman’};
var person2 = {firstName: ‘Kelly’, lastName: ‘King’};
function say(greeting) {
console.log(greeting + ‘ ‘ + this.firstName + ‘ ‘ + this.lastName);
}
say.apply(person1, [‘Hello’]); // Hello Jon Kuperman
say.apply(person2, [‘Hello’]); // Hello Kelly King
Bind:-
returns a new function(copy of function), allowing you to pass in a this array and any number of
arguments.
example:
var person1 = {firstName: ‘Jon’, lastName: ‘Kuperman’};
var person2 = {firstName: ‘Kelly’, lastName: ‘King’};
function say() {
console.log(‘Hello ‘ + this.firstName + ‘ ‘ + this.lastName);
}
var sayHelloJon = say.bind(person1);
var sayHelloKelly = say.bind(person2);
sayHelloJon(); // Hello Jon Kuperman
sayHelloKelly(); // Hello Kelly King
2
function add (a,b){
return a+b+this.c+this.d;
}
const obj = {
c:20,d:30
}
const newAdd = add.bind(obj);
console.log(newAdd(10,20));
Reference:
https://www.c-sharpcorner.com/interview-question/difference-between-call-apply-and-
bind-function-in-javascript-explain-with-example
function test() {
y = x || "Untitled Document";
}
test();
Reference:
http://adripofjavascript.com/blog/drips/an-introduction-to-iffes-immediately-invoked-function-
expressions.html
https://www.javascripttutorial.net/javascript-immediately-invoked-function-expression-iife/
Closures:-
Closures are inner function that have access to the outer function’s variable even after the
outer/parent function closed/returns.
Closures store references to the outer function’s variables
It has access to variable inside inner fun scope, var in outer fun scope and global scope
Eg:
function count(){
let count = 0;
return function(){
count++;
console.log(count);
}
3
}
What is this?:-
4
Reference:
https://betterprogramming.pub/difference-between-regular-functions-and-arrow-functions-
f65639aba256#:~:text=Since%20regular%20functions%20are%20constructible,invoked%20with
%20the%20new%20keyword.
Promise:-
Reference:
https://www.geeksforgeeks.org/javascript-promises/
Promises all:
Promises raze:
const promise1 = new Promise((resolve, reject) => {
setTimeout(resolve, 500, 'one');
});
Asyn:-
5
Async/Await is a syntactic sugar for promises, a wrapper making the code
execute more synchronously.
Await:-
*Use the fetch() method to return a promise that resolves into a Response object
Event bubbling:-
6
Event is first captured and handles by the innermost element and then propagated to the outer
elements
Supported by most of the browsers.
To stop events from Bubbling.
o event.stopPropagation()
o event.cancelBubble = true for IE < 9.
o e.stopImmediatePropagation();
Event Capturing:-
Event is first captured and handles by the outermost element and then propagated to the
innermost element.
Capturing gets enabled when phase flag is set to true for an eventListener.
o Element.addEventListener(type, handler, phase);
o Phase by default is false, means set to Bubbling
preventDefault(): -
preventDefault() prevents the default action of an event from triggering but it does not stops
event propagation to parent DOM elements.
return false:-
Regex:-
Examples:
let text = "The rain in SPAIN stays rain mainly in the plain";
let result = text.match(/ain/g);
let result1 = text.match(“ain”);
Reference: https://www.w3schools.com/jsref/jsref_obj_regexp.asp
First-Class Function:-
means that functions are treated like every other variable. It is possible to use them as
parameters in other functions, functions can return functions, and functions can be saved in
variables.
Examples:
7
// Saving a function in a variable
const myFirstFunc = () => 10
Higher-Order Function:-
Higher-order functions are functions that work with other functions, meaning that they take one
or more functions as arguments and can also return a function.
Map, reduce, and filter are all array methods in JavaScript. Each one will iterate over an array
and perform a transformation or computation. Each will return a new array based on the result
of the function.
Map:-
o The map() method is used for creating a new array from an existing one, applying a
function to each one of the elements of the first array.
Filter:-
o The filter() method takes each element in an array and it applies a conditional statement
against it. If this conditional returns true, the element gets pushed to the output array. If
the condition returns false, the element does not get pushed to the output array.
o Return type of filter must be a Boolean value.
8
Reduce:-
o The reduce() method reduces an array of values down to just one value. To get the
output value, it runs a reducer function on each element of the array.
o This function takes four arguments, but often only the first two are used.
accumulator - the returned value of the previous iteration
currentValue - the current item in the array
index - the index of the current item
array - the original array on which reduce was called
The initialValue argument is optional. If provided, it will be used as the initial
accumulator value in the first call to the callback function.
console.log(petCounts);
/*
Output:
{
dog: 2,
chicken: 3,
cat: 1,
rabbit: 1
}
*/
Reference:
https://code.tutsplus.com/tutorials/how-to-use-map-filter-reduce-in-javascript--cms-26209
Prototype:-
9
Object creation:- (http://stackoverflow.com/questions/6843951/which-way-is-best-for-creating-an-
object-in-javascript-is-var-necessary-befor)
*Constructor function
function Employee(fName) {
this.firstName = fName;
}
*Object literal (singleton)
var employee = {
name : 'Nishant'
}
*Object constructor
var employee = new Object();
employee.name = 'xx';
var MyNameSpace = {
findUserName : function(id) {},
}
console.log(MyNameSpace.findUserName());
Variable
----------
private variable -
public variable
static variable
function Test() {
var priv = "Im Private"; // private var
this.name = name; // public var
this.meth1 = function() {
// this is public meth
}
}
Test.prototype.meth2 = function() {
// this is prototype public meth
}
10
Event Delegation
Event bubbling V/s Event Capturing
e.stopPropagation();
e.stopImmediatePropagation();
JS patterns
Observer
ng watch
Singleton
ng - service, providers
Module
Revealing module pattern
Prototype
Factory
Facade
MVC, MVP, MVVM
JSLint
JSHint
ESLint
Pure function:
That doesn’t not depends on external state (eg:dom, global variable), consistently provides
same output for same input.
DE structuring :
Es6 Class:
*blue print of object, syntactical way to create a function constructor method
*Structured a way
Eg:
class Student{
constructor(name){
this.name = name;
}
}
const obj = new Student('Karthik');
11
import & export:
*code reusability,
*we can give ails name , it will over come with name conflict.
document.getElementById("myBtn").addEventListener("click", displayDate);
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
1.
basic : with backend
12
http only cookie -> backend
with credential true
2.
we get token with expire Time
host listener: refresh api: new token -> setInterval ->
1. way
2. backend as expired error given ->
micro frontend:
1.lazy loading:
2.shared module
design patterns,
solid principles
hooks,
unit testing
A polyfill is a piece of code (usually JavaScript on the Web) used to provide modern
functionality on older browsers that do not natively support it
ForEach:
function callback(element) {
console.log(element); //insert logic
}
13
Bind:
let obj = {
name: 'Jack',
};
let myFunc = function () {
console.log(`${this.name}`);
};
Function.prototype.myBind = function (obj) {
let func = this;
return function () {
func.apply(obj);
};
};
Design Patten:
<Provider store={store}>
<App />
</Provider>,
*Stateless Components
*Controlled Components
14
*React Hooks
Singleton
ng - service, providers
console.log(['10']===['10']); // false
if primitive data type will came means always false because of
reference
console.log(twoSum(arr,40));
function addN(a){
return function(b){
if(b){
return addN(a+b);
}
15
return a;
}
}
console.log(addN(1)(2)(3)(4)(5)());
Async
We use the async keyword with a function to represent that the function is
an asynchronous function. The async function returns a promise.
function bubbleSort(arr){
//Outer pass
for(let i = 0; i < arr.length; i++){
//Inner pass
for(let j = 0; j < arr.length - i - 1; j++){
//Swapping
[arr[j + 1],arr[j]] = [arr[j],arr[j + 1]]
}
}
};
return arr;
};
console.log(bubbleSort([5,3,8,4,6]));
16
sort:
var a = [10,30,50,20,30];
for(let i=0;i<=a.length;i++){
for(let j=0;j<a.length -1-i;j++){
if(a[j]> a[j+1]){
var temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
slice will create a new array of removed item also it will affect
original array2;
var array2=[6,7,8,9,0];
console.log(array2.splice(2,2)); // [8,9,0]
console.log(array2); //[6,7]
will create not affect original aarry and get selected item by
1's
var a = [3,6,8,9,2];
console.log(a.slice(2,4)); // [8,9]
console.log(a) // [3,6,8,9,2]
a
17