LayoutLogic
What is JavaScript?

JavaScript is a lightweight, interpreted, or just-in-time compiled programming language with first-class functions.

What is a variable in JavaScript, and how do you declare one?

A variable is a container for a value, which can be a number, a string, a boolean, an array, an object, or even another function.

Variables are declared using the var keyword.

You can also declare a variable using the let and const keyword, which is the preferred way to declare variables in modern JavaScript.

var x = 5;
let y = 6;
const z = 7;

let str = "Hello";

let bool = true;
What are JavaScript Data Types?

Data types are the classifications we give to the different kinds of data that we use in programming.


JavaScript has dynamic typing: you don't have to specify the data type of a variable when you declare it, as it is determined automatically. JavaScript has five primitive data types:

  • Boolean
  • Null
  • Undefined
  • Number
  • String


In addition to those, JavaScript has two special values, `Infinity` and `NaN` (not a number).

JavaScript has three types of objects:

  • Object
  • Date
  • Array


JavaScript has one type used for storing regular expressions: `RegExp`.


What is a function in JavaScript, and how do you declare one?

A function is a block of code designed to perform a particular task. A JavaScript function is executed when `something` invokes it (calls it).

You can declare a function using the `function` keyword. You can also declare a function using the arrow function syntax.

// function declaration
function myFunction(a, b) {
  return a * b;
}

// function expression or arrow function
const myFunction = function (a, b) {
  return a * b;
};
What is an array in JavaScript, and how do you create one?

An array is a special variable, which can hold more than one value at a time. You can create an array using the array literal syntax or the Array constructor.

let arr = [1, 2, 3, 4, 5];

// array constructor
let arr = new Array(1, 2, 3, 4, 5);
What is an if statement in JavaScript, and how do you use one?

An if statement is used to execute a block of code if a specified condition is true.

You can use an if statement to execute a block of code if a condition is true, or to execute a different block of code if that condition is false.

// if statement
if (condition) {
  // code block to be executed if the condition is true
}

// if else statement
if (condition) {
  // code block to be executed if the condition is true
} else {
  // code block to be executed if the condition is false
}
What is a loop in JavaScript, and how do you use one?

A loop is a programming structure that repeats a sequence of instructions until a specific condition is met.

You can use a loop to execute a block of code a number of times.

// for loop
for (let i = 0; i < 5; i++) {
  console.log(i);
}

// while loop

let i = 0;
while (i < 5) {
  console.log(i);
  i++;
}
What is a switch statement in JavaScript, and how do you use one?

A switch statement is used to perform different actions based on different conditions. You can use a switch statement to select one of many code blocks to be executed.

// switch statement
switch (expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
  // code block
}
What is break statement and continue statement in JavaScript, and how do you use?

A break statement is used to terminate a switch or a loop. You can use a break statement to terminate a switch or a loop.

// break statement
for (let i = 0; i < 5; i++) {
  if (i === 3) {
    break;
  }
  console.log(i);
}

A continue statement is used to skip the current iteration of a loop. You can use a continue statement to skip the current iteration of a loop.

// continue statement
for (let i = 0; i < 5; i++) {
  if (i === 3) {
    continue;
  }
  console.log(i);
}
What is an anonymous function in JavaScript?

An anonymous function is a function without a name. Anonymous functions are often not accessible after their initial creation.

what is event loop in JavaScript?

The event loop is a programming construct or design pattern that waits for and dispatches events or messages in a program.
It works by making a request to some internal or external "event provider" (that generally blocks the request until an event has arrived), and then it calls the relevant event handler ("dispatches the event").

What is the difference between synchronous and asynchronous code in JavaScript?

Synchronous code is executed line by line, one after the other.
Asynchronous code is executed in a non-blocking way, which means that other code can run while it is waiting for a response.

How do JavaScript primitive/object types passed in functions? or What is pass by value and pass by reference?

Primitive types are passed to functions by value, and objects are passed by reference.


Pass by value : Pass by value means that the function gets a copy of the value. If a function changes the value of an argument, it does not change the original variable.

Pass by reference : Pass by reference means that the function gets a reference to the value. If a function changes the value of an argument, it changes the original variable.

What is NaN in JavaScript?"

`NaN` stands for Not a Number. It is a property of the global object. In other words, it is a variable in global scope. The initial value of NaN is Not a Number.


When you try to convert a non-numeric string to a number, you get NaN.

Explain Implicit Type Coercion in javascript.

Implicit type coercion is the automatic or implicit conversion of values from one data type to another (such as strings to numbers, object to primitive types, and so on).


For example, when you use the + operator on a string and a number, the number is converted to a string.

// 1. Number + String
const num = 5;
const str = "5";
console.log(num + str); // 55

// 2. String + Boolean
const str = "5";
const bool = true;
console.log(str + bool); // 5true

// 3. Number + Boolean
const num = 5;
const bool = true;
console.log(num + bool); // 6

// 4. Number + Object
const num = 5;
const obj = { name: "John" };
console.log(num + obj); // 5[object Object]
How to use and implement ES6 features such as arrow functions, template literals, and destructuring?

Arrow functions are a new way to write functions in JavaScript. They are a shorter syntax for writing function expressions.

Arrow functions are always anonymous. You cannot use an arrow function as a constructor.


Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.
They were called "template strings" in prior editions of the ES2015 specification.


Destructuring is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

// arrow function
const add = (a, b) => a + b;
console.log(add(1, 2)); // 3

// template literal
const name = "John";
console.log(`Hello ${name}`); // Hello John

//destructuring
const person = {
  name: "John",
  age: 25,
  address: {
    city: "New York",
    state: "NY",
  },
};

const {
  name,
  age,
  address: { city },
} = person;
console.log(name, age, city); // John 25 New York
What is Currying in JavaScript?

Currying is a technique of evaluating function with multiple arguments, into sequence of functions with single argument.

In JavaScript, currying is a technique for creating a new function from an existing one by "pre-filling" some of its arguments.
The resulting function can be called with fewer arguments than the original, and it will return a new function that takes the remaining arguments.
This can be useful for creating specialized versions of a function that only differ by a few arguments, or for creating more flexible and composable code.

function add(a) {
  return function (b) {
    return a + b;
  };
}

const add5 = add(5);
console.log(add5(2)); // 7
console.log(add5(3)); // 8
What is an object in JavaScript, and how do you create one?

An object is a collection of properties, and a property is an association between a name (or key) and a value.

A property's value can be a function, in which case the property is known as a method.
You can create an object using the object literal syntax or the Object constructor.

// object literal
let person = {
  firstName: "John",
  lastName: "Doe",
  age: 50,
  eyeColor: "blue",
};

// object constructor
let person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
How do you create and use a callback function in JavaScript?

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.

You can create a callback function using the function keyword. You can also create a callback function using the arrow function syntax.

// callback function
function myDisplayer(some) {
  document.getElementById("demo").innerHTML = some;
}

function myCalculator(num1, num2, myCallback) {
  let sum = num1 + num2;
  myCallback(sum);
}

myCalculator(5, 5, myDisplayer);
What is a closure in JavaScript, and how do you create one?

A closure is a function having access to the parent scope, even after the parent function has closed.
You can create a closure by nesting a function inside another function.

// closure function
function add() {
  let counter = 0;
  function plus() {
    counter += 1;
  }
  return plus;
}
What is a promise in JavaScript, and how do you create one?

A promise is an object that may produce a single value some time in the future: either a resolved value, or a reason that it's not resolved (e.g., a network error occurred).
You can create a promise using the Promise constructor.

// promise function
let myPromise = new Promise(function (myResolve, myReject) {
  let x = 0;
  if (x == 0) {
    myResolve("OK");
  } else {
    myReject("Error");
  }
});

myPromise.then(
  function (value) {
    console.log(value);
  },
  function (error) {
    console.log(error);
  }
);
How do you handle events in JavaScript, such as clicks or form submissions?

You can handle events in JavaScript using event listeners.
An event listener is a procedure or function in a computer program that waits for an event to occur.
You can create an event listener using the addEventListener method.

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

function displayDate() {
  document.getElementById("demo").innerHTML = Date();
}
How do you make an HTTP request using the fetch API in JavaScript?

The fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses.

You can make an HTTP request using the fetch API by calling the fetch method.

// fetch function
fetch("https://jsonplaceholder.typicode.com/todos/1")
  .then((response) => response.json())
  .then((json) => console.log(json));
What is the difference between the var, let, and const keywords in JavaScript?

these are the following differences between the var, let, and const keywords in JavaScript:

varletconst
var is function scopedlet is block scopedconst is block scoped
var is hoistedlet is not hoistedconst is not hoisted
var can be redeclaredlet cannot be redeclaredconst cannot be redeclared
What is the difference between the == and === operators in JavaScript?

The == operator compares two values for equality after converting both values to a common type. The === operator compares two values for equality without converting the values.

// double equal
let x = 5;
let y = "5";
let z = x == y; // z will be true

// triple equal

let x = 5;
let y = "5";
let z = x === y; // z will be false
What is the difference between the null and undefined values in JavaScript?

these are the following differences between the null and undefined values in JavaScript:

nullundefined
null is an assignment valueundefined is a variable value
null is an objectundefined is a primitive
What is the difference between the map, filter, and reduce methods in JavaScript?

these are the following differences between the map, filter, and reduce methods in JavaScript:

mapfilterreduce
map creates a new arrayfilter creates a new arrayreduce creates a single value
map does not mutate the original arrayfilter does not mutate the original arrayreduce does not mutate the original array
map returns the same number of items as the original arrayfilter returns fewer items than the original arrayreduce returns a single value
// map function
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map((number) => number * 2);
console.log(doubled);
//output: [2, 4, 6, 8, 10]

// filter function
const numbers = [1, 2, 3, 4, 5];
const even = numbers.filter((number) => number % 2 === 0);
console.log(even);
//output: [2, 4]

// reduce function
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((total, number) => total + number, 0);
console.log(sum);
//output: 15
What is the difference between the call, apply, and bind methods in JavaScript?

these are the following differences between the call, apply, and bind methods in JavaScript:

callapplybind
call invokes the function immediatelyapply invokes the function immediatelybind returns a new function
call invokes the function immediatelyapply invokes the function immediatelybind does not invoke the function immediately
// call function
const person = {
  fullName: function () {
    return this.firstName + " " + this.lastName;
  },
};
const person1 = {
  firstName: "John",
  lastName: "Doe",
};
const person2 = {
  firstName: "Mary",
  lastName: "Doe",
};

person.fullName.call(person1); // Will return "John Doe"

// apply function

const person = {
  fullName: function (city, country) {
    return this.firstName + " " + this.lastName + "," + city + "," + country;
  },
};
const person1 = {
  firstName: "John",
  lastName: "Doe",
};
person.fullName.apply(person1, ["Oslo", "Norway"]); // Will return "John Doe,Oslo,Norway"

// bind function

const person = {
  fullName: function () {
    return this.firstName + " " + this.lastName;
  },
};
const person1 = {
  firstName: "John",
  lastName: "Doe",
};
const person2 = {
  firstName: "Mary",
  lastName: "Doe",
};

const x = person.fullName.bind(person1);
console.log(x()); // Will return "John Doe"
What is the difference between the for, for...in, and for...of loops in JavaScript?

these are the following differences between the for, for...in, and for...of loops in JavaScript:

forfor...infor...of
for is used to iterate over arraysfor...in is used to iterate over arraysfor...of is used to iterate over arrays
for is used to iterate over objectsfor...in is used to iterate over objectsfor...of is used to iterate over objects
// for loop
const numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
  console.log(numbers[i]);
}

// for in loop
const numbers = [1, 2, 3, 4, 5];
for (let i in numbers) {
  console.log(numbers[i]);
}

// for of loop
const numbers = [1, 2, 3, 4, 5];
for (let i of numbers) {
  console.log(i);
}
How do you manipulate the DOM (Document Object Model) using JavaScript?

You can manipulate the DOM using JavaScript by using the document object.
The document object is a global object that represents the HTML document.
You can use the document object to access the DOM tree and manipulate it.

// dom function
document.getElementById("demo").innerHTML = "Hello JavaScript!";

document.querySelector("p").innerHTML = "Hello JavaScript!";

document.querySelectorAll("p").innerHTML = "Hello JavaScript!";

document.getElementsByClassName("demo").innerHTML = "Hello JavaScript!";
How does prototypal inheritance work in JavaScript?

Prototypal inheritance is a way of implementing inheritance in JavaScript.
It is based on the concept of prototypes.
It is an alternative to classical inheritance, which is implemented in many object-oriented programming languages

// Create an object with a prototype
const animal = {
  eats: true,
  walk() {
    console.log("Animal walking");
  },
};

// Create a rabbit object with the animal prototype
const rabbit = Object.create(animal);

// Add a new property to the rabbit object
rabbit.jumps = true;

// Outputs: true
console.log(rabbit.eats);

// Outputs: true
console.log(rabbit.jumps);

// Call the walk method on the rabbit object
rabbit.walk();

// Outputs: Animal walking
How do you handle exceptions in JavaScript?

You can handle exceptions using the try...catch statement.
The try...catch statement allows you to define a block of code to be tested for errors while it is being executed.
The try...catch statement has two main parts: the try block and the catch block.
The try block contains the code that you want to test for errors.
The catch block contains the code that you want to run if an error occurs in the try block.

// exception function
try {
  console.log("This line is executed...");
  throw new Error("Whoops!");
  console.log("This line is not...");
} catch (err) {
  console.log("There was an error...");
}

//output: This line is executed...
//output: There was an error...
What is difference between a function declaration and a function expression in JavaScript?

The main difference between a function declaration and a function expression is the function name, which can be omitted in function expressions to create anonymous functions.
Function declarations are hoisted and can be called before they are defined.
Function expressions are not hoisted and cannot be called before they are defined.

// function declaration
function sum(a, b) {
  return a + b;
}

// function expression

const sum = function (a, b) {
  return a + b;
};
What is the difference between shallow and deep copying in JavaScript?

The main difference between shallow and deep copying is that shallow copying creates a new object that stores references to the original object’s properties, while deep copying creates a new object and copies the original object’s properties.
Shallow copying is faster than deep copying.
Deep copying is preferred over shallow copying when you want to make sure that changes to a copied object don’t affect the original object.

// shallow copy
const person = {
  name: "John",
  age: 25,
  address: {
    city: "New York",
    state: "NY",
  },
};

const person2 = { ...person };
person2.name = "Peter";
person2.address.city = "Boston";

console.log(person);
console.log(person2);

//output: { name: 'John', age: 25, address: { city: 'Boston', state: 'NY' } }
//output: { name: 'Peter', age: 25, address: { city: 'Boston', state: 'NY' } }

// deep copy

const person = {
  name: "John",
  age: 25,
  address: {
    city: "New York",
    state: "NY",
  },
};

const person2 = JSON.parse(JSON.stringify(person));
person2.name = "Peter";
person2.address.city = "Boston";

console.log(person);
console.log(person2);

//output: { name: 'John', age: 25, address: { city: 'New York', state: 'NY' } }
//output: { name: 'Peter', age: 25, address: { city: 'Boston', state: 'NY' } }
How do you implement debouncing in JavaScript?

You can implement debouncing in JavaScript by using the setTimeout() function.
The setTimeout() function is used to delay the execution of a function for a specified number of milliseconds.
The setTimeout() function is called at the beginning of the debounced function.
The setTimeout() function is called with the delay time as the first argument and the debounced function as the second argument.
The setTimeout() function returns a timer ID.
The timer ID is stored in a variable.
If the setTimeout() function is called again before the delay time has passed, the timer ID is cleared.

// debouncing function
function debounce(func, delay) {
  let inDebounce;
  return function () {
    const context = this;
    const args = arguments;
    clearTimeout(inDebounce);
    inDebounce = setTimeout(() => func.apply(context, args), delay);
  };
}

const run = debounce(() => console.log("debounce"), 1000);
run();
run();
run();

//output: debounce
How do you implement throttling in JavaScript?

You can implement throttling in JavaScript by using the setTimeout() function.
The setTimeout() function is used to delay the execution of a function for a specified number of milliseconds.
The setTimeout() function is called at the beginning of the throttled function.
The setTimeout() function is called with the delay time as the first argument and the throttled function as the second argument.
The setTimeout() function returns a timer ID.
The timer ID is stored in a variable.
If the setTimeout() function is called again before the delay time has passed, the timer ID is cleared.

// throttling function
function throttle(func, limit) {
  let inThrottle;
  return function () {
    const args = arguments;
    const context = this;
    if (!inThrottle) {
      func.apply(context, args);
      inThrottle = true;
      setTimeout(() => (inThrottle = false), limit);
    }
  };
}

const run = throttle(() => console.log("throttle"), 1000);
run();
run();
run();
What is the difference between a promise and a callback in JavaScript?

The main difference between a promise and a callback is that a promise can be resolved or rejected only once, while a callback can be called multiple times.
A promise is an object that represents the eventual completion or failure of an asynchronous operation.
A promise can be in one of three states: pending, fulfilled, or rejected.
A callback is a function passed as an argument to another function.
A callback is executed after another function has finished.

How do you handle asynchronous code using async/await in JavaScript?

You can handle asynchronous code using async/await in JavaScript by using the async and await keywords.
The async keyword is used to define an asynchronous function.
The await keyword is used to wait for a Promise.
The await keyword can only be used inside an asynchronous function.

// async await function
async function getTodos() {
  const response = await fetch("https://jsonplaceholder.typicode.com/todos");
  const data = await response.json();
  console.log(data);
}
getTodos();

//output: [{ userId: 1, id: 1, title: 'delectus aut autem', completed: false }, ...]
What is `strict mode` in JavaScript, and what are the advantages of using it?

Strict mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a “strict” operating context.


This strict context prevents certain actions from being taken and throws more exceptions.
It is not a statement, but a literal expression, ignored by earlier versions of JavaScript.
The purpose of “use strict” is to indicate that the code should be executed in “strict mode”.


With strict mode, you can not, for example, use undeclared variables.
Strict mode makes it easier to write “secure” JavaScript.

// Strict mode can be enabled in two ways:

// 1. On the entire script: Add the string "use strict" as the first statement in a JavaScript file or at the top of a script block.

"use strict";
// code here

// 2. On a function: Add the string "use strict" as the first statement in a function.

function strict() {
  "use strict";
  // code here
}
What is difference between Window and Document in JavaScript?

The difference between Window and Document in JavaScript is that the Window object represents an open window in a browser and the Document object represents the HTML document loaded in a window.


The Window object is the global object in JavaScript.
The Document object is the root node of the HTML document.


Window is the global object which contains all the global variables, functions, location, history, etc.
Document come under the window object and it is the root node of the HTML document.

What is difference between `Local Storage` and `Session Storage` in JavaScript?

These are the differences between Local Storage and Session Storage in JavaScript:


Local StorageSession Storage
Local Storage is a permanent storage.Session Storage is a temporary storage.
Local Storage is not cleared when the browser is closed.Session Storage is cleared when the browser is closed.
How do you create and use a higher-order function in JavaScript?

A higher-order function is a function that takes a function as an argument, or returns a function.
You can create a higher-order function using the function keyword.
You can also create a higher-order function using the arrow function syntax.

//create a function that takes a function as an argument and calls it
function callTwice(func) {
  func();
  func();
}
function laugh() {
  console.log("hahahahahahahahahaha!");
}
callTwice(laugh);
//output: hahahahahahahahahaha! hahahahahahahahahaha!

// higher order function
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map((number) => number * 2);
console.log(doubled);
//output: [2, 4, 6, 8, 10]

const numbers = [1, 2, 3, 4, 5];
const even = numbers.filter((number) => number % 2 === 0);
console.log(even);
//output: [2, 4]

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((total, number) => total + number, 0);
console.log(sum);
//output: 15
How do you optimize the performance of a JavaScript application?

You can optimize the performance of a JavaScript application by minimizing the number of HTTP requests, minimizing the amount of JavaScript, and minimizing the use of CSS expressions.


You can also optimize the performance of a JavaScript application by using a content delivery network, or CDN.


You can also optimize the performance of a JavaScript application by reducing the DOM access.


You can also optimize the performance of a JavaScript application by avoiding global variables.


You can also optimize the performance of a JavaScript application by minifying JavaScript and CSS.

How do you create and use a generator in JavaScript?

A generator is a function that can stop midway and then continue from where it stopped. You can create a generator using the function keyword.
You can also create a generator using the arrow function syntax.

// generator function
function* generator() {
  yield 1;
  yield 2;
  yield 3;
}
const gen = generator();
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);

//output: 1 2 3
How do you create and use a set in JavaScript?

A set is an object that stores unique values of any type. You can create a set using the Set constructor.

// set function
const set = new Set([1, 2, 3, 4, 5]);
console.log(set.has(1)); // true
console.log(set.has(5)); // true
console.log(set.has(6)); // false
How do you integrate a third-party API into a JavaScript application?

You can integrate a third-party API into a JavaScript application by using the fetch API, the XMLHttpRequest object, or the jQuery library.

// integrate third party api using
fetch("https://jsonplaceholder.typicode.com/todos/1")
  .then((response) => response.json())
  .then((json) => console.log(json));

// integrate third party api using XMLHttpRequest
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/todos/1");
xhr.responseType = "json";
xhr.onload = function () {
  console.log(xhr.response);
};
xhr.send();

// integrate third party api using jQuery
$.getJSON("https://jsonplaceholder.typicode.com/todos/1", function (json) {
  console.log(json);
});
What is event delegation in JavaScript?

Event delegation is a technique in which you add an event listener to a parent element instead of adding it to multiple child elements.

Event delegation is useful because it allows you to avoid adding event listeners to specific nodes; therefore, it improves performance.

Event delegation is also useful because it allows you to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

<ul id="parent-element">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

<script>
  document.getElementById('parent-element').addEventListener('click', function(event) {
    // Check if the clicked element is a list item
    if (event.target.tagName === 'LI') {
      // The clicked element is a list item, do something here
    }
  });
</script>

In this example, we have attached a single click event listener to the parent `ul` element. When any of the `li` elements are clicked, the event listener will be triggered and we can check the event.target property to see which element was actually clicked. This allows us to handle the click event for all of the `li` elements without having to attach a separate event listener to each one.

How do you perform deep copying of objects in JavaScript?

You can perform deep copying of objects in JavaScript by using the JSON.parse and JSON.stringify methods.

You can also perform deep copying of objects in JavaScript by using the lodash library.

// lodash deep copy
const person = {
  name: "John",
  age: 25,
  address: {
    city: "New York",
    state: "NY",
  },
};

const person2 = _.cloneDeep(person);
person2.name = "Peter";
person2.address.city = "Boston";

console.log(person);
console.log(person2);

//output: { name: 'John', age: 25, address: { city: 'New York', state: 'NY' } }
//output: { name: 'Peter', age: 25, address: { city: 'Boston', state: 'NY' } }
How do you create private variables in JavaScript?

You can create private variables in JavaScript by using closures.

// private variables
const Person = (function () {
  const privateData = new WeakMap();
  class Person {
    constructor(name) {
      privateData.set(this, { name });
    }
    getName() {
      return privateData.get(this).name;
    }
  }
  return Person;
})();

const person = new Person("John");
console.log(person.getName());

//output: John
How do you optimize an algorithm for time and space complexity in JavaScript?

You can optimize an algorithm for time complexity in JavaScript by using memoization.

// memoization function
function memoize(fn) {
  const cache = {};
  return function (...args) {
    if (cache[args]) {
      return cache[args];
    }
    const result = fn.apply(this, args);
    cache[args] = result;
    return result;
  };
}

function add(a, b) {
  return a + b;
}

const memoizedAdd = memoize(add);

console.log(memoizedAdd(1, 2));
console.log(memoizedAdd(1, 2));

//output: 3
//output: 3