Javascript Interview Cheatsheet
Important and basics concepts in Javascript which can help in preparation for interviews.
Scope
The scope is the current context of execution in which values and expressions are "visible" or can be referenced. Scope of the variables means where the variables are available for use and if it is not in current scope, it will not be available for use. Scopes can also be layered in a hierarchy, so that child scopes have access to parent scopes, but not vice versa.
let value1 = 20;
function add(){
console.log(value1); // 20
let value2 = 30;
console.log(value2);
}
add();
console.log(value1); // 20
console.log(value2); //ReferenceError: value2 is not defined
/* as value2 have function scope so will be available for use only in function
add() and outside add() it will not be available for use while value1 have
global scope so it can be accessed anywhere in the code.
*/
Scopes can also be layered in a hierarchy, so that child scopes have access to parent scopes, but not vice versa.
Types of Scopes
Global Scope: Variables declared globally(outside any function) have global scope.
Function Scope: Variables declared inside the function have function scope, we can't access them outside the function.
Block Scope: Variables declared with let and const belongs to block scope. Variables declared inside { } block can't be accessed from outside the block. Variables declared with var keyword have no block scope.
Global Scope
A variable that can be accessed anywhere in the program is known as a variable with global scope. Globally scoped variables can be defined using any of the three keywords: let, const, and var.
let value1 = 20;
console.log(value1); //20
/* value1 is globally scoped as it is defined outside any function, block, or
module and thus will be available to use anywhere in code */
Function Scope
Variable that is declared inside a function is known as function/local scope. You can only access a local variable within a function. If you try to access any variable defined inside a function from outside or another function, it throws an error.
function add(){
let value = 30; // declared value locally
console.log(value); //30
}
add();
console.log(value); //ReferenceError: value is not defined
/* accessing the local variable value from outside it will throw an
error */
Block Scope
Variables declared inside a { } block cannot be accessed from outside the block. The block scope does not work with the var keyword. You can either use let or const keywords for that.
let value = 10; //declaring a variable globally
let add = ()=>{
let value = 20; // declaring a variable within block
console.log(value); //20
}
console.log(value); //10
/* variable value defined within the curly braces {} has a boundary only
within that curly braces, hence console gives varied results when used
within and outside the scope */
Lexical scope
Lexical scope is the ability of the inner function to access the outer scope in which it is defined. Ability for a function scope to access variables from the parent scope.
Consider,
function showLastName() {
const lastName = "Singh";
return lastName;
}
function displayFullName() {
const fullName = "Shubham" + lastName;
return fullName;
}
console.log(displayFullName()); // Uncaught ReferenceError: lastName is not defined
displayFullName() in the snippet above returned an Uncaught ReferenceError. The error returned because only code within an item's lexical scope can access the item. Therefore, neither the displayFullName() function nor its internal code can access the lastName variable because lastName got defined in a different scope. lastName’s definition space is showLastName() while displayFullName()’s lexical scope is the global environment.
Let's consider this example:
function showLastName() {
const lastName = "Singh";
return lastName;
}
function displayFullName() {
const fullName = "Shubham" + showLastName();
return fullName;
}
console.log(displayFullName()); //ShubhamSingh
Above, displayFullName() successfully returned "ShubhamSingh" because displayFullName() and showLastName() are in the same lexical scope.
In other words, displayFullName() could invoke showLastName() because the two functions are both defined in the global scope.
Note:
In example above, displayFullName() did not gain access to showLastName()'s lastName variable. Instead, displayFullName() invoked showLastName() — which then returned the content of its lastName variable.
Scope Chaining
When a variable is used in Javascript, JavaScript engine uses scopes to find out the exact location or accessibility of variables and that particular process is known as Scope Chain. If it could not find the variable, it will look into the outer scope and will continue to do so until it finds the variable or reaches global scope.
If it’s still could not find the variable, it will either implicitly declare the variable in the global scope (if not in strict mode) or return an error.
let value1 = 20; //global variable
function main_function() {
let value2 = 30; // local variable
let nested_function = () => {
console.log(value2); // 30
}
let another_nested_function = () => {
console.log(value1); //20
}
nested_function();
another_nested_function();
}
main_function();
Single Threading & Call Stack
Javascript is a single threaded language that can be non-blocking. Single threaded means it has only one call stack. Whatever is on the top of the call stack is run first. JS is a single threaded which means only one statement is executed at a time. In other words, we can say Javascript is by default synchronous in nature.
var a = 2;
var b = 4;
function add() {
var ans = a + b;
return ans;
}
add();
JS creates an Execution Context(Global Context) before executing the code, this Execution Context is passed to what is called a Call Stack - where the main execution happens.[FILO] The Global Context is created in two phases:
1) Memory Component - this is where all the variables and functions are stored as key : value pair. Key can be variable and value is its current value.
Here in the first phase, variable 'a' will be stored as 'undefined'. This is stored in the Memory Component as a : undefined
Here the values for these variables are not assigned by the Memory component. This happens in the next phase. For now, variables are assigned as undefined and for functions, the whole function itself is added.
2) Code Component - this is where the execution of each line of code happens. In this phase, the values are assigned to the variables.
Now the value of a becomes 2 from undefined and will be stored as - a : 2
JS executes the code one line at a time. JS can't do tasks more than one at a time. So here it is, this is what single-threaded means.
JS executes code in a specific order. The first line is executed and only when this is finished it goes for the next line. It cannot jump to the 3rd line before executing the 2nd line. This is known as synchronous.
So there you go - 'synchronous single-threaded'.
Now when it meets a function, a new Execution Context like the first one is created inside the first Execution Context, with the same two phases, and the procedure is the same.
Hoisting
It refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, prior to execution of the code. Hoisting allows functions to be safely used in code before they are declared.
Function Hoisting
name();
function name(){
console.log("unknown");
}
// displays 'unknown' in console
Variable Hositing
Var
Var variables are hoisted at the top of their scope and initialized with value undefined.
console.log(name);
var name = "Shubham";
JavaScript interpret it as:-
var name;
console.log(name); // name is undefined
name = "Shubham";
let & const
let & const variable declarations are also hoisted to top. Unlike var which is initialized as undefined, the let keyword is not initialized. So if we try to use let variable before declarations, we'll get Reference Error.
console.log(names);
let names = "Shubham";
// ReferenceError: names is not defined
Temporal Dead Zone
Temporal Dead Zone is the period of time during which the let and const declarations cannot be accessed. Temporal Dead Zone starts when the code execution enters the block which contains the let or const declaration and continues until the declaration has executed.
Variables declared using let and the constants declared using const are hoisted but are in a TDZ. This prevents them from being accessed before their declaration has actually been executed during the step-by-step execution of the code.
Hope you found this article helpful 🙂, Suggestions and feedback are highly welcomed .
Thanks for reading & Keep Coding !