Scope and Closures Flashcards

1
Q

What is scope? Provide an example.

A

Нуждата от ясно дефинирани правила за това къде се запазват променливите и как се намират по-късно се нарича скоуп.

Scope: space or environment in which a certain variable is declared (variable environment in case of function). Scope defines the area, where functions, variables, and such are available.
ope.

function grandfather() {
 var name = 'Hammad';

// likes is not accessible here

 function parent() {
 // name is accessible here
 // likes is not accessible here
 function child() {
 // Innermost level of the scope chain
 // name is also accessible here
 var likes = 'Coding';
 }
 }
}
console.log(likes); // ReferenceError: likes is not defined
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is Global scope?

A

Global scope

  1. outside of any function or block
  2. variables declared in global scope are accessible everywhere
const me = “My and miself”
const year = 2022
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is Function scope?

A

Function scope

  1. Variables are accessible only inside functions, not outside.
  2. Also called local scope
function calcAge (birthYear ) {
 Const now = 2022;
 Const age = now- birthYear; return age;
 } 

Console.log(now) // Reference Error

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is Block scope?

A

Block scope (ES6)

  1. Variables are accessible only inside the block (block scoped). However, this applies only to let and const variables
  2. Functions are also block-scoped, only in strict mode
  3. We use block scope because we need to declare variables as close as possible (as local as possible) to where they will be used
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is Scope chain?

A

Variable lookup in scope chain:

  1. Every scope always has access to all the variables from all its outer scopes (parent’s scopes).
  2. Variables are not copied from one scope to another. Instead, scopes simply look up in the scope chain until they find the variable that they need, and then they use it
  3. A certain scope will never ever have access to variables of on inner scope
  4. The way that we can access variables depends on where the scope is placed ( where it is written in the code)
  5. Scope chain only works upwards not sideways
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is lexical scope? What is lexing-time?

A

Lexical Scope means that in a nested group of functions, the inner functions have access to the variables and other resources of their parent scope even if the parent function has returned. Lexical scope is sometimes also referred to as Static Scope.

  • Lexical scope това е мястото където нашата променлива е написана
  • lexical scope is scope that is defined at lexing time
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is the difference between const, let and var?

A

Demonstrate the difference between var and let

  • Var is function scoped
  • Let and const are block scoped
 if (true) {
 var a = 42;
 }
 console.log(a); // a = 42
if (true) {
 let b = 34;
}

console.log(b); // ReferenceError: b is not defined

const foo = () =\> {
 var c = 12;
};

console.log(c); // c= 12

const foo = () =\> {
 const c = 12;
};

console.log(c); // ReferenceError: c is not defined

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is the difference between == and ===?

A
  • The strict equality operator (===) checks whether its two operands are equal, returning a Boolean result. Unlike the equality operator, the strict equality operator always considers operands of different types to be different.
  • The most notable difference between this operator and the equality (==) operator is that if the operands are of different types, the == operator attempts to convert them to the same type before comparing.

• If the operands are of different types, return false.
• If both operands are objects, return true only if they refer to the same object.
• If both operands are null or both operands are undefined, return true.
• If either operand is NaN, return false.
• Otherwise, compare the two operand’s values:
o Numbers must have the same numeric values. +0 and -0 are considered to be the same value.
o Strings must have the same characters in the same order.
o Booleans must be both true or both false.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is type coercion?

A

Type coercion is the automatic or implicit conversion of values from one data type to another (such as strings to numbers). Type conversion is similar to type coercion because they both convert values from one data type to another with one key difference — type coercion is implicit whereas type conversion can be either implicit or explicit.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is variable and function hoisting?

A

Hoisting is the process of collecting variables by the JavaScript compiler.

JS engine прочита, че имаме някаква променлива, преди тя да бъде декларирана и използвана, но само отчита този факт. Ако променливата е декларирана като let или const и ние се опитаме да я достъпим преди декларация– връща грешка, ако е var – undefined.

Var дава възможността стойността да бъде достъпена като undefined стойност.
Function declaration-а може да бъде изпълнен, защото е деклариран на едно място и директно се качва най-отгоре в нашия скоуп. Важно е да се знае, че се качват само техните декларации, а по-късно се достъпват и стойностите им или се извикват функциите.

Hoisted
Var hoisted = ‘Telerik Academy’
Not hoisted

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What will be printed in the console?

console.log(addDecl(2, 3));

function addDecl(a, b) {
 return a + b;
}
A

Output: 5

This is because we are able to call function declaration before it was defined in the code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is hoisted and what is not?

A
  • Everything in JavaScript is hoisted (even let and const )
  • let and const are in the temporal dead zone before declared, so they will throw an error if accessed before declared
  • Let and const are accessible only after declaration.
  • Var and function declarations function a() are accessible even before they are declared
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What will be printed in the console?

console.log(addExpr(2, 3));

var addExpr = function (a, b) {
 return a + b;
};
A

TypeError: addExpr is not a function

Because addExpr is declared as var it is hoisted, and its value is undefined.

So, we are trying to do this: undefined(2, 3).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What will be printed in the console?

console.log(addArrow(2, 3));

const addArrow = (a, b) => a + b;

A

ReferenceError: Cannot access ‘addArrow’ before initialization

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is a closure?

• Explain what is closure and how it’s connected to scopes.

A

Formal: A closure is the closed-over variable environment of the execution context in which a function was created, even after that execution context is gone.

Less formal: A closure gives function access to all the variables of its parent function, even after that parent function has returned. The function keeps a reference to its outer scope, which preserves the scope chain throughout time.

Less former: A closure makes sure that a function doesn’t lose connection to variables that existed at the function’s birthplace.

Less formal: A closure is like a backpack that a function carries around wherever it goes. This backpack has all the variables that were present in the environment where the function was created.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is Scoping?

A

Scoping: how our program’s variables are organized and accessed, “where do variables live?” or “where can we access a certain variable, and where not”.

17
Q

What will be printed in the console?

console.log(addExpr(2, 3));

const addExpr = function (a, b) {
 return a + b;
};
A

Cannot access ‘addExpr’ before initialization

18
Q

What will be printed in the console?

console.log(addArrow(2, 3));

var addArrow = (a, b) => a + b;

A

TypeError: addArrow is not a function

Because addArrow is declared as var it is hoisted, and its value is undefined.

So, we are trying to do this: undefined(2, 3).

19
Q

What will be printed on the console?

let d = 4;
function two() {
let d;
d = 5;

console.log(d);
}
two();
console.log(d);

A

5

4

20
Q

What will be printed on the console?

let a = 1;

function one() {
 a = 2;
 var a = 3;
 console.log(a);
}

one();
console.log(a);

A

3

1

21
Q

What will be printed on the console?

let f = 5;

 function three() {
 let f = g = 6;
 console.log(f);
 }

three();
console.log(g, f);

A
22
Q

Demonstrate how to provide access to a variable’s value outside the function it is defined in.

A
23
Q

In a given piece of code, determine if closure exists and identify it:

(function () {
 const header = document.querySelector('h1');
 header.style.color = 'red';

document.querySelector(‘body’).addEventListener(‘click’, function () {
header.style.color = ‘blue’;
});
})();

A

There is a closure over the IIFE function - the function in the event listener has access to the header variable even when IIFE is gone.

The header is in the backpack of the event listener function.

24
Q

Provide an example of closure:

A

const boardingPassengers = function (n, wait) {
const perGroup = n / 3;
setTimeout(function () {
console.log(We are now boarding all ${n} passengers.);
console.log(There are 3 groups, each with ${perGroup} passengers.);
}, wait * 1000);

console.log(Will start boarding in ${**wait**} seconds.);
};

const perGroup = 1000;
boardingPassengers(180, 3);
  1. perGroup Is registered
  2. setTimeout is registered
  3. console.log(Will start boarding in ${wait} seconds.); is executed
  4. after 3 seconds function is executed: function () {
    * console.log(We are now boarding all ${n} passengers.);*
    * console.log(There are 3 groups, each with ${perGroup} passengers.);*
    * },*
  5. This function has access to the n, wait and perGroup from its parent boardingPassengers function
  6. The closure has priority over the scopes that is why the function looks first in its closure for perGroup and not in the scope chain (in this case global scope)