0% found this document useful (0 votes)
3 views17 pages

Javascript_new

The document provides a comprehensive overview of JavaScript concepts including data types, variable declarations (var, let, const), hoisting, strict mode, function invocation methods (call, apply, bind), asynchronous programming with promises and async/await, event handling, regular expressions, first-class and higher-order functions, array methods (map, filter, reduce), and object creation. It explains the differences between regular and arrow functions, the use of closures, and the prototype chain for inheritance. Additionally, it covers the importance of IIFE for data privacy and the mechanisms of event bubbling and capturing.

Uploaded by

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

Javascript_new

The document provides a comprehensive overview of JavaScript concepts including data types, variable declarations (var, let, const), hoisting, strict mode, function invocation methods (call, apply, bind), asynchronous programming with promises and async/await, event handling, regular expressions, first-class and higher-order functions, array methods (map, filter, reduce), and object creation. It explains the differences between regular and arrow functions, the use of closures, and the prototype chain for inheritance. Additionally, it covers the importance of IIFE for data privacy and the mechanisms of event bubbling and capturing.

Uploaded by

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

Javascript

*************

Datatypes:-

Type typeOf Evaluation Primitive


Null object Yes
undefined undefined Yes
Boolean boolean Yes
String string Yes
Number number Yes
Array object No
Function function No
Object object No
Symbol symbol No

var, let, const: -

 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 & Apply :-

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

short circuiting with || (Logical OR):-

function test() {
y = x || "Untitled Document";
}
test();

IIFE (immediately invoked function expression):-

 It executes immediately after it is created.


 The primary reason to use an IIFE is to obtain data privacy or limit the scope of variable
 Its all about variable scoping, can write without concern of variable name,
 To Avoid Polluting the Global Scope
 An IIFE can have a name. However, it cannot be invoked again after execution

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
}

const test = count();


console.log(test());
console.log(test());
console.log(test());
console.log(test());
console.log(test());
console.log(test());
*The variables declared inside a closure are not garbage collected.
Too many closures can slow down your application. This is actually caused by duplication of code in
the memory.

const createBase = (base) => {


return function(innVal){
return innVal+base;
}
}
var addSix = createBase(6);
console.log(addSix(10));

What is this?:-

 In JavaScript, the this keyword refers to an object.


 It’s refers to the current execution context.

 Which object depends on how this is being invoked (used or called).


 The this keyword refers to different objects depending on how it is used:
o In an object method, this refers to the object.
o Alone, this refers to the global object
o In a function, this refers to the global object.
o In a function, in strict mode, this is undefined
o In an event, this refers to the element that received the event.
o Methods like call(), apply(), and bind() can refer this to any object.
Its referee to the execution context

The Difference Between Regular Functions and Arrow Functions:-

 1. Syntax – Arrow uses fat arrow syntax () no binding of this..


 2. Arguments binding(Regular Functions)
 3. Use of this keyword
 4. Using new keyword, Since regular functions are constructible however the arrow functions
are only callable and not constructible.
 5. No duplicate named parameters => in non strict mode

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:-

 Promises are used to handle asynchronous operations in JS.


 Resulting resolved or failure.
 Also provides better error handling than callbacks
 Implements Observer pattern
 A Promise has four states:
o fulfilled: Action related to the promise succeeded
o rejected: Action related to the promise failed
o pending: Promise is still pending i.e. not fulfilled or rejected yet
o settled: Promise has fulfilled or rejected

Reference:
https://www.geeksforgeeks.org/javascript-promises/

Promises all:

const promise1 = Promise.resolve(3);


const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 'foo');
});

Promise.all([promise1, promise2, promise3]).then((values) => {


console.log(values);
});

Promises raze:
const promise1 = new Promise((resolve, reject) => {
setTimeout(resolve, 500, 'one');
});

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


setTimeout(resolve, 100, 'two');
});

Promise.race([promise1, promise2]).then((value) => {


console.log(value);
// Both resolve, but promise2 is faster
});

Asyn:-

5
Async/Await is a syntactic sugar for promises, a wrapper making the code
execute more synchronously.

 Async functions will always return a value.


 It makes sure that a promise is returned and if it is not returned then javascript automatically
wraps it in a promise which is resolved with its value.

Await:-

 Await function is used to wait for the promise.


 It could be used within the async block only. It makes the code wait until the promise returns a
result. It only makes the async block wait.
 It only return promise

const prom = () =>{


return new Promise((resolve,reject) =>{
setTimeout(()=>{
resolve(2);
},0);
});
}
async function test(){
console.log(1);
await prom()
.then((value)=>{
console.log(value)
}).catch((err)=>{
console.log(err)
})
console.log(3);
}
test();

*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:-

 Does what peventDefault() and stopPropagation() methods does

Regex:-

 A regular expression is a pattern of characters.


 The pattern is used to do pattern-matching "search-and-replace" functions on text.
 In JavaScript, a RegExp Object is a pattern with Properties and Methods.

o The search() method returns the position of the first match.


o exec()Tests for a match in a string. Returns the first match
o test() Tests for a match in a string. Returns true or false
o toString() Returns the string value of the regular expression

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

// Passing a function as an argument


const mySecondFunc = (funcParam) => {
return console.log(funcParam())
}

// Returning a function from a function


const myThirdFunc = () => {
return () => console.log('Hello from returned function')
}

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, Filter and Reduce:-

 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.

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


const doubled = numbers.map(item => item * 2);
console.log(doubled); // [2, 4, 6, 8]
for condition it will “evaluate value”
eg: const data = [2,4,5,7,9,10];
const new = map.data((val)=>{
return val>10;
})
Console.log(new) => [true,false]…like this

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.

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


const evens = numbers.filter(item => item % 2 === 0);
console.log(evens); // [2, 4]

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.

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


const sum = numbers.reduce(function (result, item) {
return result + item;
}, 0);
console.log(sum); // 10

 In the next example, reduce() is used to transform an array of strings into a


single object that shows how many times each string appears in the array.
var pets = ['dog', 'chicken', 'cat', 'dog', 'chicken', 'chicken', 'rabbit'];

var petCounts = pets.reduce(function(obj, pet){


if (!obj[pet]) {
obj[pet] = 1;
} else {
obj[pet]++;
}
return obj;
}, {});

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:-

 Every JavaScript object has an internal property called [[Prototype]]


 Used for inheritance in JS (Prototypal Inh)
 You can think of the prototype attribute as the lineage or the parent
 A prototype is an object from which other objects inherit properties

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';

How to empty an array in JavaScript?


arrayList = []; --> does not affect other references
arrayList.length = 0; --> make all array empty (even references)
arrayList.splice(0, arrayList.length); --> make all array empty (even references)

Singleton design pattern

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.staticVar = "im static var"; // static var


Test.prototype.staticVar = "im static var"; // static var

Test.prototype.meth2 = function() {
// this is prototype public meth
}

DOM Event Propagation

10
Event Delegation
Event bubbling V/s Event Capturing
e.stopPropagation();
e.stopImmediatePropagation();

JS patterns

*It’s are reusable solutions to commonly occurring problems in software design

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 :

That makes unpack the value,


Its makes copy of the obj or arr by assigning then to new own variable.

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.

The addEventListener() method attaches an event handler to the


specified element.

document.getElementById("myBtn").addEventListener("click", displayDate);

function displayDate() {
document.getElementById("demo").innerHTML = Date();
}

*custom bind using prototype


*fetch (get and post)

Constructor Prototype call


function add(a,b){
this.a = a;
this.b = b;
this.total = function(){
return this.a+this.b;
}
}

add.prototype.multipply = function (){


return this.a*this.b;
}
let n = new add(10,20);
console.log(n.multipply());

let a = 10+20+”30”; // 3030;


let b = “30”+20+20; // 302020

http only cookie -> backend


with credential true

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 ->

code -> validate

micro frontend:
1.lazy loading:

2.shared module

1.upload new crash file ||

design patterns,
solid principles
hooks,
unit testing

Object.freeze works on values, and more specifically, object values. It makes


an object immutable, i.e. you cannot change its properties.

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 myForEach(array, callback) {


for (let i = 0; i < array.length; i++) {
callback(array[i]);
}
}

function callback(element) {
console.log(element); //insert logic
}

const array = [2, 4, 6, 8, 10];


myForEach(array, callback);

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);
};
};

let newFunc = myFunc.myBind(obj)


newFunc()

Design Patten:

design patterns are repeatable solutions to commonly occurring problems in


software development.

*The higher-order component pattern

*The provider pattern

 The provider pattern in React is an advanced pattern


used to share global data across multiple components
in the React component tree.

<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

Sum of two number in single loop:

function twoSum(nums, target){


let numObject = {}
for(let eachNum in nums){
let otherNum = target - nums[eachNum] //we'll check for
otherNum in the object and if it's there, we got it and can push
in our result array.
if(otherNum in numObject){
let resultArr = [];
resultArr.push(otherNum, nums[eachNum])
return resultArr;
}
numObject[nums[eachNum]] = eachNum
//NB! adding key/value has to go after the if-statement to
avoid adding the same index twice. We add the value or a new pair
on each iteration.
}
return "not found";
}

const arr = [10,30,40,50,60];

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++){

//Value comparison using ascending order

if(arr[j + 1] < arr[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

You might also like