javaScript Interview Cheat Sheet

ยท

7 min read

javaScript Interview Cheat Sheet

Hello Guys & Girls ๐Ÿ™‹๐Ÿปโ€โ™‚๏ธ๐Ÿ˜ƒ In this Article We are going to see some of the common topics that are asked in interviews many times, ie(scope,Single threading , call stack, and hoisting).

What is Scope ?

Scope is kind variable "visibiliity". its this idea depending on where you declare the variable ? othe pice of code may or may not have access the value of that variable.

Types of Scopes

  • Function / Local scope
  • Block Scope
  • Global Scope
  • Lexical Scope

Function Scope or Local Scope

: A variable declare inside the function and it can access only inside the function

For example:

function printMsg(){
var a = "Tony";
let b = "Bruce";
const c = "Banner";

console.log(`Top 3 Smartest super heroes are ${a}, ${b}, ${c}`);
}
printMsg(); //  Top 3 Smartest super heroes are Tony, Bruce, Banner

console.log(`Top 3 Smartest super heroes are ${a}, ${b}, ${c}`); // Undefined

inside the function we have access to all three variables. But outside the bound of that function we dont have access. we will get error. those variables are scoped to that function.

let's see another example:

let bird = 'Madarin Duck';

function birdWatch(){
let bird = 'Golden Phesant';
console.log(bird);
}

birdWatch(); // Golden Phesant.
console.log(bird); // Madarin Duck.

as you can see here we have Two scopes, two bird variable one is inside the birdWatch() and another one is top of that. and both are printing the results, one bird variable inside the birdWatch() can be access only inside that function it scoped to that function.

another example:

function employee(){
let name = 'Micky';
let age = 34;
let role = 'Web devloper';
console.log(`His name is ${name} , age ${age} and he is ${role} in our company`);
}

function student(){
let name = 'Sanjay';
let age = 12;
let role = 'Monitor';
console.log(`${name} is ${age} and he is ${role} of our class`);
}

employee(); // His name is Micky ,age 34 and he is Web devloper in our company
student(); // Sanjay is 12 and he is Monitor of our class

as you can see we are using same variables in both functions and its printing the output, this is happening because variables are scoped to their function , they can accessible only inside that function this is why we are getting output and not any error.

Block Scope

Now let's come back on let,var & const to discuss one of the main distinct between let and const compare to var. so this is it Block scope this is very very important concept how variables work in javaScript. so let's start with simple example :

*if(true){
let animal = 'Lion';
console.log(animal); // Lion
}
console.log(animal); // Uncaught RefrenceEroor: animal is not defined

so what this tell us? it tells us variable animal is scoped to the block { }. so that's how let and const behaves. if you replace let with const it behaves same .

if(true){
const animal = 'Lion';
console.log(animal); // Lion
}
console.log(animal); // Uncaught RefrenceEroor: animal is not defined

Now lets see how it behaves with var :

if(true){
var animal = 'Lion';
console.log(animal); // Lion
}
console.log(animal); // Lion

it work with both case Lion is printed in block and outside of the block. so this tells us let & const have different scoping rules than var. back in day before let & const we only had var. and var is scoped to functions(). there is no block scope for var.

Global scope:

A variable declared outside of the function or top of the program consider as Global variable. Let's see an example below:

// program to print a text 
let a = "hello";

function greet () {
    console.log(a);
}

greet(); // hello

In the above program, variable a is declared at the top of a program and is a global variable. It means the variable a can be used anywhere in the program.

The value of a global variable can be changed inside a function. For example:

// program to show the change in global variable
let a = "hello";

function greet() {
    a = 3;
}

// before the function call
console.log(a); // hello

//after the function call
greet();
console.log(a); // 3

In the above program, variable a is a global variable. The value of a is hello. Then the variable a is accessed inside a function and the value changes to 3.

Hence, the value of a changes after changing it inside the function.

Note: It is a good practice to avoid using global variables because the value of a global variable can change in different areas in the program. It can introduce unknown results in the program.

In JavaScript, a variable can also be used without declaring it. If a variable is used without declaring it, that variable automatically becomes a global variable.

for example:

function greet() {
    a = "hello"
}

greet();

console.log(a); // hello

Lexical Scope

Next up we have different type of scope Lexical Scope , this one pretty simple and straight forward ,

Lexical scope is the ability for a function scope to access variables from the parent scope. We call the child function to be lexically bound by that of the parent function.

lets try to understand by example:

function outer() {
  let movie = "Iron Man";
  function inner() {
    console.log(movie.toUpperCase());
  }
  inner();
}

outer(); // IRONMAN

As you can see inner function do not have variable movie but it stills manage to print variable movie's value, and variable movie is declared inside outer function. it is happening because of lexical scope.

Single Threaded

"javaScript is a Synchronousnus , single-threaded language"

-Single threaded means js runs one command at a time.

-Synchronous single-threaded means js can run one command at a time in a specific order, that means it will go to the next line only when current line is executed.

That means Synchronousnus , single-threaded language.

Call Stack

"Everything in javasScript happens inside an Execution Context" & javaScript isnt possible without this Execution Context.

you can assume this execution context to be a big box or container in which whole js code executed. and it has 2 component

1) Variable environment or Memory Component : this is the place where variable & functions stored as key value pair.

key : value;

2) Code or Thread of execution : in this place where code get executed one line at a time.

Screenshot 2022-09-13 at 1.13.13 AM.png

so execution context is created in two phases. 1) Creation Phase / Memory Creation Phase: in the first phase of memory creation phase js allocate memory to all variable and functions. it will reserve space for variables and functions.

2) Code Execution Phase: In this phase js runs through program line by line and it executes code now. so this is the place where all functions and calculations in program is done.

Note:- functions are heart of js program, & whenever new function is invoked new execution context is created

Don't you think all of this is too much to manage for js engine. ? actually it is very difficult to manage for js engine but it does very beautifully,

so it handle everything to manage this execution context creation and deletion control via STACK. and this is know as Call Stack . so call stack is like stack. it is a stack & every time we have Global Execution Context bottom of the stack. and like we read before on every function() invocation new Execution context get created. lets see in diagram.

Screenshot 2022-09-13 at 2.08.11 AM.png

and once function() is done it immediately popped out from call stack. and after completing whole program Global Execution Context also popped out from stack.

call stack is only for managing the execution context.

" Call Stack Maintains the order of execution of execution contexts"

Hoisting

Something i need to cover that you shouldn't stress about if it confuse you. let's try to understand throughout the example:

let x = 7;
function comics(){
    console.log('Ghost Rider');
}
comics(); // Ghost Rider
console.log(x) // 7

output is as expected . Now lets see something magical in js.

comics(); // Ghost Rider
console.log(x); // Undefined
var x = 7;
function comics() {
  console.log("Ghost Rider");
}

nox x is undefined but function() get printed. why is that ?? so this all magic & intresting thing known as Hoisting in js, so Hoisting is phenomena in js by which you can access variable & function even before intialing . you can access it without any error.

console.log(comics); // whole code of function is printed 
console.log(x); // Undefined
var x = 7;
function comics() {
  console.log("Ghost Rider");
}
console.log(comics);
/*function comics() {
  console.log("Ghost Rider");
} */

var x is undefined but function is not , why is that ?? so remember "Everything in javasScript happens inside an Execution Context" & its created in two phases 1) Memory component / Variable enviroment 2) code / Thread of execution so answer and whole concept of hoisting lie there.

Thanks for Reading this Blog. if you like it leave a like, comment. okay that's it i am going away bye ๐Ÿ‘‹๐Ÿป.

Let's connect on Twitter || Linkedin || Instagram โค๏ธ ๐Ÿ™‹๐Ÿปโ€โ™‚๏ธ

ย