javascript

PHOTO EMBED

Sun Jul 23 2023 09:25:02 GMT+0000 (Coordinated Universal Time)

Saved by @nelson22

Hoisting 

JavaScript Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, prior to execution of the code.

- variable can be declared after it is been used
- Hoisting is JavaScript default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).

x = 5
var x

- Variables defined with let and const are hoisted to the top of the block, but not initialized.
- Meaning: The block of code is aware of the variable, but it cannot be used until it has been declared.
- Using a let variable before it is declared will result in a ReferenceError.
- The variable is in a "temporal dead zone" from the start of the block until it is declared

- Below code will result in ReferenceError
carName = "Volvo";
let carName;

- Below code will not run
carName = "Volvo";
const carName;

-----------------------------------------------------------------

Ten ES6 features

let and const Keywords
Arrow Functions
Default Parameters
Template Literals
Destructuring Assignment
Multi-line Strings
Enhanced Object Literals
Promises
Classes
Modules

-----------------------------------------------------------------

Enhanced Object Literals

- ES6 provides enhanced object literals which make it easy to quickly create objects with properties inside the curly braces.

function getMobile(manufacturer, model, year) {
   return {
      manufacturer,
      model,
      year
   }
}
getMobile("Samsung", "Galaxy", "2020");

-----------------------------------------------------------------

Promise

- Promises are used to handle asynchronous operations in JavaScript.

- A Promise has four states: 
	1. fulfilled: Action related to the promise succeeded
	2. rejected: Action related to the promise failed
	3. pending: Promise is still pending i.e. not fulfilled or rejected yet
	4. settled: Promise has fulfilled or rejected
    
- A promise can be created using Promise constructor
var promise = new Promise(function(resolve, reject){
     //do something
});

- Parameters 
	- Promise constructor takes only one argument which is a callback function (and that callback function is also referred as anonymous function too).
	- Callback function takes two arguments, resolve and reject
	- Perform operations inside the callback function and if everything went well then call resolve.
	- If desired operations do not go well then call reject.

-----------------------------------------------------------------

Palindrome 

A palindrome is used to verify a sequence of numbers, strings, or letters that are read left to right and right to left to match the same characters or return the same sequence of characters. In simple terms, when the numbers, strings, or characters are reversed that return the same result as the original numbers or characters, it is called a Palindrome. For example, NITIN, 123454321, madam, etc. Suppose we have a word, madam. When we read the word madam from the forward and the backward end, it returns the same string. Therefore, we can refer to the string or number as the Palindrome.

let palindrome = function(word){
  let len = word.length;
  let first = word.substring(0, Math.floor(len/2));
  let last = word.substring(Math.floor(len/2) + 1, len);
  let arr = last.split('').reverse().join('');
  return first === arr
}

console.log(palindrome('dever'));
console.log(palindrome('nitin'));
console.log(palindrome('radar'));

-----------------------------------------------------------------

Array methods

1. toString() - this method converts an array into a string
const num = [1, 2, 3, 4];
console.log(num.toString());  // result "1,2,3,4"

2. join() - this method joins all elements inside the array
const num = [1, 2, 3, 4];
let b = num.join('_');
console.log(b);  // result "1_2_3_4"

3. pop() - this method removes the last element inside array
const num = [1, 2, 3, 4];
let r = num.pop()
console.log(num, r);  // result [1, 2, 3], 4
here 'r' returns poped element

4. push() - this method pushes an element to last of an array
const num = [1, 2, 3, 4];
num.push(5);
console.log(num);  // result [1, 2, 3, 4, 5]

5. shift() - this method removes the first element from array
const num = [1, 2, 3, 4];
let s = num.shift();
console.log(num, s);  // result [2, 3, 4], 1

6. unshift() - this adds an element to start of the array
const num = [1, 2, 3, 4];
let u = num.unshift(9);
console.log(num, u);  // result [9, 1, 2, 3, 4], 5
here u returns the length of array

7. delete - this operator deletes the element from array with matching index
const num = [1, 2, 3, 4];
console.log(num.length);  // result 4
delete num[0];
console.log(num);  // result [undefined, 2, 3, 4]
console.log(num.length);  // result 4
here the length of an array remains same after delete

8. concat() - this method joins two or more arrays and returns an array
const num = [1, 2, 3, 4];
const num2 = [21, 22, 23];
const num3 = [31, 32];
const newArr = num.concat(num2, num3);
console.log(newArr);  // result [1, 2, 3, 4, 21, 22, 23, 31, 32]

9. sort() - this method sorts the array considering the first digit
const num = [1, 22, 54, 9, 3];
console.log(num.sort());  // result [1, 22, 3, 54, 9]
const assending = (a, b) => {
	return a - b
}
console.log(num.sort(assending));  // result [1, 3, 9, 22, 54]

10. reverse() - this method reverses the array elements
const num = [1, 2, 3, 4, 5];
console.log(num.reverse());  // result [5, 4, 3, 2, 1]

11. splice() - this method can be used to remove and add elements to the array. It takes in 3 arguments. First is the index from where to start, second is number of elements to delete, rest of the arguments are elements to be added to array.
const num = [1, 2, 3, 4, 5];
let deletedElements = num.splice(2, 3, 33, 34, 35, 36);
console.log(num);  // result [1, 2, 33, 34, 35, 36]
console.log(deletedElements);  // result [3, 4, 5]
It returns an array of deleted items

12. slice() - this method slices a part of array and retruns new array
const num = [1,2,3,4,5,6,7];
const newnum = num.slice(2, 8);
console.log(newnum);  // result [3, 4, 5, 6, 7]

Array Looping

1. forEach
let num = [1, 2, 3, 4];
num.forEach((ele) => {
  console.log(ele);
})

2. Array.from() - this method returns an array from an html collection
const name = "Nelson";
const nameArr = Array.from(name);
console.log(nameArr);  // result [N, e, l, s, o, n]

3. for of 
const num = [1,2,3,4,5,6,7];
for(let i of num){
  console.log(i)
}

4. for in - this will return the index
const num = [1,2,3,4,5,6,7];
for(let i in num){
  console.log(i)
} 

5. map
const num = [1,2,3,4,5,6,7];
const newNum = num.map((ele, index, arr) => {
  return ele + 1
})
console.log(newNum);  // result [2,3,4,5,6,7,8]

6. filter
const num = [1,2,34,4,56,68,7];
let singleDigit = num.filter(val => {
  return val < 10
})
console.log(singleDigit);  // result [1,2,4,7]

7. reduce
const num = [1, 2, 3, 4];
const sum = num.reduce((a, b) => {
  return a + b;
})
console.log(sum);

Difference between map and forEach
- The map() method returns a new array, whereas the forEach() method does not return a new array.
- The map() method is used to transform the elements of an array, whereas the forEach() method is used to loop through the elements of an array.
- The map() method can be used with other array methods, such as the filter() method, whereas the forEach() method cannot be used with other array methods.

-----------------------------------------------------------------

Shallow copy and Deep copy

- Shallow Copy: When a reference variable is copied into a new reference variable using the assignment operator, a shallow copy of the referenced object is created. In simple words, a reference variable mainly stores the address of the object it refers to. When a new reference variable is assigned the value of the old reference variable, the address stored in the old reference variable is copied into the new one. This means both the old and new reference variable point to the same object in memory. As a result if the state of the object changes through any of the reference variables it is reflected for both. Let us take an example to understand it better.

var employee = {
	eid: "E102",
	ename: "Jack",
	eaddress: "New York",
	salary: 50000
}

console.log("Employee=> ", employee);
var newEmployee = employee; // Shallow copy
console.log("New Employee=> ", newEmployee);

console.log("---------After modification----------");
newEmployee.ename = "Beck";
console.log("Employee=> ", employee);
console.log("New Employee=> ", newEmployee);
// Name of the employee as well as newEmployee is changed.


- Deep Copy: Unlike the shallow copy, deep copy makes a copy of all the members of the old object, allocates separate memory location for the new object and then assigns the copied members to the new object. In this way, both the objects are independent of each other and in case of any modification to either one the other is not affected. Also, if one of the objects is deleted the other still remains in the memory. Now to create a deep copy of an object in JavaScript we use JSON.parse() and JSON.stringify() methods. 

var employee = {
    eid: "E102",
    ename: "Jack",
    eaddress: "New York",
    salary: 50000
}
console.log("=========Deep Copy========");
var newEmployee = JSON.parse(JSON.stringify(employee));
console.log("Employee=> ", employee);
console.log("New Employee=> ", newEmployee);
console.log("---------After modification---------");
newEmployee.ename = "Beck";
newEmployee.salary = 70000;
console.log("Employee=> ", employee);
console.log("New Employee=> ", newEmployee);


-----------------------------------------------------------------

Closure 

- Closures are defined as inner functions that have access to variables and parameters of outer function even after the outer function has returned.
- A closure is a function having access to the parent scope, even after the parent function has closed.

const add = (function () {
  let counter = 0;
  return function () {counter += 1; return counter}
})();

add();
add();
add();

// the counter is 3

-----------------------------------------------------------------

Event Loop

The event loop is a process that waits for the Call Stack to be clear before pushing callbacks from the Task Queue to the Call Stack. Once the Stack is clear, the event loop triggers and checks the Task Queue for available callbacks.
-----------------------------------------------------------------

Types of scopes

- global scope
- functional scope
- block scope

-----------------------------------------------------------------

Prototype

-----------------------------------------------------------------

Promice function

-----------------------------------------------------------------

Progressive web app

-----------------------------------------------------------------

Service worker in data pulling

-----------------------------------------------------------------

Web acceablity

-----------------------------------------------------------------

saga

-----------------------------------------------------------------

thunk

-----------------------------------------------------------------

function expression
functions which are declared using equals to or assigned to a variable
const abc = () => {

}
var xyz = function(){

}
same is for class expressions







content_copyCOPY