JavaScript is an interesting language to learn but when it comes to an interview lot of the time we did not know how the internal working of JavaScript code. This is the reason we fail in the interviews. In this article, we will be discussing some of the most asked interview questions and trying to answer them.
Q. Explain Scope in JavaScript.
Scope determines the visibility or accessibility of a variable or other resource in the area of your code.
JavaScript variables are lexically scoped, meaning that we can determine a variableโs scope from where it is declared in the source code. (This is not entirely true: var variables are not lexically scoped, but we will discuss that shortly.)
There are different types of scopes in the JavaScript
- Global Scope: There's only one Global scope in the JavaScript document. The area outside all the functions is considered the global scope and the variables defined inside the global scope can be accessed and altered in any other scope.
// global scope
var firstName = "Prakash";
function fullName(){
console.log(`${firstName} Naikwadi`); // firstName is accessible here
}
fullName();
- Function Scope Whenever you declare a variable in a function, the variable is visible only within the function. You can't access it outside the function. var is the keyword to define a variable for function-scope accessibility.
function foo(){
var fruit ='apple';
console.log('inside function: ',fruit);
}
foo(); //inside function: apple
console.log(fruit); //error: fruit is not defined
- Block Scope Block scope is the area within if, switch conditions, or for and while loops. Generally speaking, whenever you see {curly brackets}, it is a block. In ES6, const and let keywords allow developers to declare variables in the block scope, which means those variables exist only within the corresponding block.
function foo(){
if(true){
var fruit1 = 'apple'; //exist in function scope
const fruit2 = 'banana'; //exist in block scope
let fruit3 = 'strawberry'; //exist in block scope
}
console.log(fruit1);
console.log(fruit2);
console.log(fruit3);
}
foo();
//result:
//apple
//error: fruit2 is not defined
//error: fruit3 is not defined
Q. Explain Scope Chaining in JavaScript.
JavaScript allows nested blocks and therefore nested scopes. Nested scopes create a scope tree or scope chain.
Consider the code below, which nests multiple block statements:
if (true) {
const foo = "foo";
console.log(foo); // "foo"
if (true) {
const bar = "bar";
console.log(foo); // "foo"
if (true) {
console.log(foo, bar); // "foo bar"
}
}
}
As expected, we can access variables from their direct scope (the scope where they get declared). We can also access variables from their inner scopes (the scopes that nest within their direct scope). That is, we can access variables from the scope they get declared in and from every inner scope.
Q. Single threading in JavaScript
Javascript is a single-threaded language. This means it has one call stack and one memory heap. As expected, it executes code in order and must finish executing a piece of code before moving on to the next. It's synchronous, but at times that can be harmful. For example, if a function takes a while to execute or has to wait on something, it freezes everything up in the meanwhile.
A good example of this happening is the window alert function. alert("Hello World")
You can't interact with the webpage at all until you hit OK and dismiss the alert. You're stuck.
Q. Call Stack in JavaScript
- To manage these execution contexts i.e if there is a function inside a function, then inside the execution context there will be another execution context call stack used.
- When the program starts running the
global execution context
is created and pushed into the call stack. - So, at the bottom their always
Global Execution Context
. - When the function is executed its execution context is pushed into the call stack and popped when execution is returned.
- At last Global Execution contexts also get removed when the code is finished.
Call stack maintains the order of execution of execution contexts.
Q. Hoisting in JavaScript
For understanding hoisting we have to understand how execution context is created into memory.
Execution Context in JavaScript
Everything in JS happens inside an execution context. We can consider execution context as a big box inside which the whole JS code is executed.
Execution context consists of two components
Memory Component (Environment Variable): It consists of variables and values in the form of
key:value
pair and also functions consist ofkey:value
pair (e.g. function_Name : {whole_function_code})Code Component (Thread of Execution): It's like a thread in which one line at a time is executed.
There are two types of execution context in JavaScript
Global Execution Context: Whenever the JavaScript engine receives a script file, it first creates a default Execution Context known as the Global Execution Context (GEC). The GEC is the base/default Execution Context where all JavaScript code that is not inside of a function gets executed.
For every JavaScript file, there can only be one GEC.
Function Execution Context: Whenever a function is called, the JavaScript engine creates a different type of Execution Context known as a Function Execution Context (FEC) within the GEC to evaluate and execute the code within that function.
Since every function call gets its own FEC, there can be more than one FEC in the run-time of a script.
How are Execution Contexts Created?
It is created in two phases
- Memory Creation Phase:
- In this phase, JS Engine will allocate memory to each variable and function.
- Also, JS Engine will give
undefined
as a value to the variables and givethe whole function code
to the function variable. - Let's see the following Example Code
var firstName = "Prakash"; var lastName = "Naikwadi"; function getName(){ console.log(firstName, lastName); } getName();
- The above code first gets parsed and the
Global Execution Context
is created in thememory creation phase
and memory is allocated to variables with the default value ofundefined
and functions with value aswhole function code
.
This memory creation or allocation phase or parsing of the whole JavaScript code is known as hoisting.
Thank You For Reading๐คฉ
If you like this article, please give thumps up๐
Comment down your suggestions๐