What is scope? Provide an example.
Нуждата от ясно дефинирани правила за това къде се запазват променливите и как се намират по-късно се нарича скоуп.
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 herevar likes = 'Coding'; } } } console.log(likes); // ReferenceError: likes is not defined
What is Global scope?
Global scope
const me = “My and miself” const year = 2022
What is Function scope?
Function scope
function calcAge (birthYear ) {
Const now = 2022;
Const age = now- birthYear; return age;
} Console.log(now) // Reference Error
What is Block scope?
Block scope (ES6)
What is Scope chain?
Variable lookup in scope chain:
What is lexical scope? What is lexing-time?
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.
What is the difference between const, let and var?
Demonstrate the difference between var and let
if (true) {
var a = 42;
}
console.log(a); // a = 42if (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
What is the difference between == and ===?
• 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.
What is type coercion?
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.
What is variable and function hoisting?
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
What will be printed in the console?
console.log(addDecl(2, 3));
function addDecl(a, b) {
return a + b;
}Output: 5
This is because we are able to call function declaration before it was defined in the code.
What is hoisted and what is not?
What will be printed in the console?
console.log(addExpr(2, 3));
var addExpr = function (a, b) {
return a + b;
};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).
What will be printed in the console?
console.log(addArrow(2, 3));
const addArrow = (a, b) => a + b;
ReferenceError: Cannot access ‘addArrow’ before initialization
What is a closure?
• Explain what is closure and how it’s connected to scopes.
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.
What is Scoping?
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”.
What will be printed in the console?
console.log(addExpr(2, 3));
const addExpr = function (a, b) {
return a + b;
};Cannot access ‘addExpr’ before initialization
What will be printed in the console?
console.log(addArrow(2, 3));
var addArrow = (a, b) => a + b;
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).
What will be printed on the console?
let d = 4;
function two() {
let d;
d = 5;console.log(d);
}
two();
console.log(d);
5
4
What will be printed on the console?
let a = 1;
function one() {
a = 2;
var a = 3;
console.log(a);
}one();
console.log(a);
3
1
What will be printed on the console?
let f = 5;
function three() {
let f = g = 6;
console.log(f);
}three();
console.log(g, f);
Demonstrate how to provide access to a variable’s value outside the function it is defined in.
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’;
});
})();
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.
Provide an example of closure:
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);
Will start boarding in ${wait} seconds.); is executedWe are now boarding all ${n} passengers.);*There are 3 groups, each with ${perGroup} passengers.);*