0% found this document useful (0 votes)
2K views

Js Revison Topics

Uploaded by

ahmed.high212
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2K views

Js Revison Topics

Uploaded by

ahmed.high212
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

console.

log(a); // ReferenceError: Cannot access 'a' before initialization


console.log(b); // prints undefined as expected

let a = 10;
var b = 15;

 Both a and b are actually initialized as undefined in hoisting stage. But var b is inside the storage space of
GLOBAL, and a is in a separate memory object called script, where it can be accessed only after assigning
some value to it first ie. one can access 'a' only if it is assigned. Thus, it throws error.

Temporal Dead Zone : Time since when the let variable was hoisted until it is initialized some value.

Variable Shadowing: In JavaScript, variable shadowing occurs


when a variable with the same name as a variable in a higher
scope is declared in a lower scope.

Illegal Shadowing: This occurs when trying to shadow a variable using var
within the same scope where that variable is already defined using let or
const.

Hoisting: In JavaScript, hoisting is a behavior where variable and function


declarations are moved to the top of their containing scope during the
compilation phase. However, only the declarations are hoisted, not the
initializations or assignments. In third example, console.log(a); will result in
undefined because the variable a is hoisted to the top but not initialized until
later in the code (var a = 10;).
The map() method in JavaScript creates a new array populated with the
results of calling a provided function on every element in the calling array. It
doesn't modify the original array but returns a new modified array based on
the callback function's logic.
Question 2: Array.filter() Explanation: The filter() method creates a new
array with all elements that pass the test implemented by the provided
function. It returns a filtered array based on the condition specified in the
callback function, where only elements that satisfy the condition are
included.

Question 3: Array.reduce() Explanation: The reduce() method executes a


reducer function (that you provide) on each element of the array, resulting in
a single output value. It's often used for aggregating data, such as
calculating a sum, by iterating through the array and accumulating the
results based on the logic in the callback function .

Question 4: Map Polyfill

Question 5: Filter Polyfill

Question 6: Reduce Polyfill

What is JS First Class Function

First-class functions if functions in that language are treated like other variables
o Can be stored as a value in a variable
o Can be returned by another function
o Can be passed as a function's argument

Immediately Invoked Function Expressions (IIFE


Immediately Invoked Function Expressions (IIFE) are JavaScript functions that are executed immediately after they are defined. They are
typically used to create a local scope for variables to prevent them from polluting the global scope.

Function Scope
JavaScript has function scope: Each function creates a new scope.
Variables defined inside a function are not accessible (visible) from outside the function.

Variables declared with var, let and const are quite similar when declared inside a function.

Question 5 : Function Hoisting

// Without Hoisting:
function functionName() {
console.log("work at tech");
}

functionName(); // function is called after declaring it

// With Hoisting:
functionName(); // function is called before declaring it

function functionName() {
console.log("work at tech");
}

When we defined variable present in the local scope we will not go and check in the global scope

var x = 21;
var fun = function () {
console.log(x);
var x = 20;
};
fun();

gives UNDEFINED
JavaScript Callbacks
A callback is a function passed as an argument to another function

A callback function can run after another function has finished

Suppose you want to do a calculation, and then display the result.

You could call a calculator function (myCalculator), save the result, and then call another function (myDisplayer) to display the result:

you could call a calculator function ( myCalculator), and let the calculator function call the display function ( myDisplayer):

The problem with the first example above, is that you have to call two functions to display the result.

The problem with the second example, is that you cannot prevent the calculator function from displaying the result.

Now it is time to bring in a callback.

Using a callback, you could call the calculator function ( myCalculator) with a callback (myCallback), and let the calculator function run the
callback after the calculation is finished:

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. A closure is a function that has access to its parent function's
variables, even after the parent function has returned. This allows the inner function
to remember the state of its parent function, even if the parent function has
finished executing.
Closure scope chain
Every closure has three scopes:

 Local scope (Own scope)


 Enclosing scope (can be block, function, or module scope)
 Global scope

we can say that closures have access to all outer function scopes.
function createBase(num) {
return function (innerNum) {
console.log(innerNum + num);
};
}
var addSix = createBase(6);
addSix(10);
addSix(20);

function find() {
let a = [];
for (let i = 0; i < 1000000; i++) {
a[i] = i * i;
}
return function (index) {
console.log(a[index]);
};
}
const closure = find();
console.time("6");
closure(6);
console.timeEnd("6");
console.time("50");
closure(50);
console.timeEnd("50");

Performance Issue:
 Initializing and populating the array a happens every time find is called. This is inefficient, especially if the array is
large and you need to call find multiple times.

Explanation
1. Function find:
o This function initializes an array a and populates it with the squares of numbers from 0 to 999,999.
o After populating the array, find returns an inner function that takes an index and logs the corresponding
value from the array a.
2. Closure Creation:
o When you call find(), it returns the inner function. This inner function retains access to the array a
because of the closure.
o The variable a is enclosed in the inner function, meaning it is "remembered" even after find has finished
executing.
3. Using the Closure:
o const closure = find(); calls find and assigns the returned inner function to the variable closure.
o When you call closure(6);, it logs the value of a[6], which is 36 (since 6 * 6 = 36).
o Similarly, closure(50); logs the value of a[50], which is 2500 (since 50 * 50 = 2500).
4. Timing the Execution:
o console.time("6"); and console.timeEnd("6"); are used to measure the time taken to retrieve
and log the value of a[6].
o Similarly, console.time("50"); and console.timeEnd("50"); measure the time taken to
retrieve and log the value of a[50].

Why Use Closures Here?

 Efficient Data Retrieval:


o The closure allows you to precompute and store a large set of data (squares of numbers) and efficiently
retrieve specific values as needed.
 Encapsulation:
o The array a is encapsulated within the find function. It is not accessible directly from outside, ensuring that
it can only be accessed and modified through the returned function.

for (var i = 0; i < 3; i++) {


function inner(i) {
setTimeout(function (log) {
console.log(i); // 3 times 3
}, i * 1000);
}
inner(i);
}

The Outer for Loop

 The loop iterates 3 times (i = 0, 1, 2).

The Inner Function inner(i)

 The inner function is defined and immediately called with the current value of i.
 It sets up a setTimeout to log the value of i after i seconds.
The setTimeout Function

 setTimeout schedules the provided function to execute after a specified delay (i * 1000
milliseconds).

Detailed Execution

First Iteration (i = 0)

1. inner(0) is called.
2. setTimeout schedules console.log(0) to run after 0 seconds.

Second Iteration (i = 1)

1. inner(1) is called.
2. setTimeout schedules console.log(1) to run after 1 second.

Third Iteration (i = 2)

1. inner(2) is called.
2. setTimeout schedules console.log(2) to run after 2 seconds.

Why the Original Example Logs 3 Three Times

If we remove the inner function and use the setTimeout directly in the loop with var i, like
this:
function a() {
for (var i = 0; i < 3; i++) {
setTimeout(function (log) {
console.log(i); // 0,1,2
}, i * 1000);
}
}

This would log 3 three times. Here’s why:

 var is function-scoped or globally-scoped, not block-scoped. By the time the


setTimeout functions execute, the loop has completed and i is 3.
 All the scheduled functions reference the same i from the outer scope, which ends up
being 3 after the loop completes.

1. Module Pattern
The Module Pattern is a fundamental design pattern in JavaScript that allows you to create private and public methods and variables within a single object. This pattern is particularly
useful when you want to encapsulate the implementation details and expose a simple public API.
var module = (function () {
function privateMethod() {
console.log("private");
}
return {
publicMethod: function () {
console.log("public");
privateMethod();
},
};
})();
module.publicMethod();

function counter() {
var _counter = 0;

function add(increment) {
_counter += increment;
}

function retrive() {
return "Counter = " + _counter;
}

return {
add,
retrive,
};
}
const c = counter();
c.add(5);
c.add(10);
console.log(c.retrive());
function counter() {
var _counter = 0;

function add(increment) {
_counter += increment;
}

function retrive() {
return "Counter = " + _counter;
}

return {
add,
retrive,
};
}
const c = counter();
c.add(5);
c.add(10);
console.log(c.retrive());

diff between closure and scope


Currying Explanation: Currying is a technique in functional programming
where a function with multiple arguments is transformed into a sequence of
functions, each taking a single argument.

You might also like