Skip to content

Instantly share code, notes, and snippets.

@vikas-git
Last active June 18, 2024 07:14
Show Gist options
  • Save vikas-git/4eef384a730d7c4e2414494c55fc1352 to your computer and use it in GitHub Desktop.
Save vikas-git/4eef384a730d7c4e2414494c55fc1352 to your computer and use it in GitHub Desktop.

Content:

Closures

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

function init() {
  var name = "Mozilla"; // name is a local variable created by init
  function displayName() {
    // displayName() is the inner function, that forms the closure
    console.log(name); // use variable declared in the parent function
  }
  displayName();
}
init();

Callback

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

Arrow function

Arrow function is the way to write function in shorter syntax.

// normal functions like
function hello(){
    return “hello world”
}

hello =  function(){
    return “hello world”
}
// arrow functions like
hello = () => {
	return “Hello world”
}

hello = () => "Hello World!";

Var vs Let vs Const

Var Let Const
The scope of a var variable is functional or global scope. The scope of a let variable is block scope. The scope of a const variable is block scope.
It can be updated and re-declared in the same scope. It can be updated but cannot be re-declared in the same scope. It can neither be updated or re-declared in any scope.
It can be declared without initialization. It can be declared without initialization. It cannot be declared without initialization.
It can be accessed without initialization as its default value is “undefined”. It cannot be accessed without initialization otherwise it will give ‘referenceError’. It cannot be accessed without initialization, as it cannot be declared without initialization.
These variables are hoisted. These variables are hoisted but stay in the temporal dead zone untill the initialization. These variables are hoisted but stays in the temporal dead zone until the initialization.

Spread Operator

Spread syntax can be used when all elements from an object or array need to be included in a new array or object, or should be applied one-by-one in a function call's arguments list. There are three distinct places that accept the spread syntax:

Function arguments list (myFunction(a, ...iterableObj, b))
Array literals ([1, ...iterableObj, '4', 'five', 6])
Object literals ({ ...obj, key: 'value' })
// Examples
myFunction(a, ...iterableObj, b)
[1, ...iterableObj, '4', 'five', 6]
{ ...obj, key: 'value' }

// 1
function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

console.log(sum(...numbers));
// output: 6

console.log(sum.apply(null, numbers));
// Expected output: 6

// 2
const obj = { key1: "value1" };
const array = [...obj]; // TypeError: obj is not iterable

// 3
const array = [1, 2, 3];
const obj = { ...array }; // { 0: 1, 1: 2, 2: 3 }

// 4
const obj = { ...true, ..."test", ...10 };
// { '0': 't', '1': 'e', '2': 's', '3': 't' }

// 5
const arr = [1, 2, 3];
const arr2 = [...arr]; // like arr.slice()

arr2.push(4);
// arr2 becomes [1, 2, 3, 4]
// arr remains unaffected

Rest Operator

The rest parameter syntax allows a function to accept an indefinite number of arguments as an array.

// syntax
function f(a, b, ...theArgs) {
  // …
}

// 1.
function sum(...theArgs) {
  let total = 0;
  for (const arg of theArgs) {
    total += arg;
  }
  return total;
}

console.log(sum(1, 2, 3));
// Expected output: 6

console.log(sum(1, 2, 3, 4));
// Expected output: 10


// 2.
function myFun(a, b, ...manyMoreArgs) {
  console.log("a", a); // a, one
  console.log("b", b); // b, two
  console.log("manyMoreArgs", manyMoreArgs); // manyMoreArgs, ["three", "four", "five", "six"]
}
myFun("one", "two", "three", "four", "five", "six");

// 3. 
myFun("one", "two");
// a, "one"
// b, "two"
// manyMoreArgs, [] <-- still an array

// 4.

function fun1(...theArgs) {
  console.log(theArgs.length);
}

fun1(); // 0
fun1(5); // 1
fun1(5, 6, 7); // 3

A function definition can only have one rest parameter, and the rest parameter must be the last parameter in the function definition.

function wrong1(...one, ...wrong) {}
function wrong2(...wrong, arg2, arg3) {}

SetInterval vs Settimeout

setInterval fires again and again in intervals, while setTimeout only fires once

setTimeout(function () {
    something();
}, 1000); // Execute something() 1 second later.

setInterval(function () {
    somethingElse();
}, 2000); // Execute somethingElse() every 2 seconds.

Map vs Set

Use a Set when your dataset needs to be composed of unique values

const organization = new Set();

organization.add('org1');
organization.add('org2');
organization.add('org3');
organization.add('org1');
organization.add('org3');
organization.add('org1');

for(let org of organization){
  console.log(org);
}
// Output
// org1
// org2
// org3

Use a Map when you have pairs of associated data. You map the keys to the values

const dogs = new Map([['fluffy', 10], ['barkie', 13]]);

dogs.forEach((value, key) => console.log(key, value));

MAP vs OBJECT

An Object is also a collection of key value pairs and can fulfill often the same purpose as a Map can (which is creating key-value pairs). However, there are some key differences between a Map and an Object:

  • Map is built in Iterable, this allows it to use the for of loop or its implementation of the forEach() method which an plain JS Object cannot use.
  • Map has some nice built in methods on its prototype which makes working with it very nicely. Because al Objects inherit from Object.prototype is has access to more useful methods. For example, the size() method on Map returns the number of keys in the Map.

Higher order function

A higher order function is a function that takes one or more functions as arguments, or returns a function as its result. There are several different types of higher order functions like map and reduce.

// Callback function, passed as a parameter in the higher order function
function callbackFunction(){
    console.log('I am  a callback function');
}

// higher order function
function higherOrderFunction(func){
    console.log('I am higher order function')
    func()
}

higherOrderFunction(callbackFunction);

Template literals

Laxical scope

Promises

Hoisting

iife function

Hashing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment