Skip to content

Instantly share code, notes, and snippets.

@nurmdrafi
Last active February 17, 2023 19:33
Show Gist options
  • Save nurmdrafi/6077c01c1783726d872116382153b9a7 to your computer and use it in GitHub Desktop.
Save nurmdrafi/6077c01c1783726d872116382153b9a7 to your computer and use it in GitHub Desktop.

Related Links

🔗 Awesome JavaScript Interviews 🔥🔥🔥

🔗 JavaScript Interview Questions 436+ - Github

🔗 JavaScript Interview Questions 70+ - Javapoint

🔗 Most Frequent JavaScript Interview Questions 64+ - Interviewbit

🔗 JavaScript Modern Interview Code Challenges - Github

🔗 JavaScript Coding Challenges for Beginners (Codewares) 57+ - Github

🔗 JavaScript Output Test - Github

🔗 JavaScript MCQ Questions 155+ - Github

🔗 JavaScript MCQ Questions 150+ - Javapoint

🔗 React Interview Questions 80+ - Javapoint

🔗 HR Interview Questions 50+ - Javapoint

🔗 HTML Tags Complete Reference

Questions

Q: What is JavaScript?

what is javascript

Q: What is Abstraction?

An abstraction is a way of hiding the implementation details and showing only the functionality to the users. In other words, it ignores the irrelevant details and shows only the required one.

JavaScript is a highly abstract programming language. In JavaScript we don't have to do resource management, memory allocation & garbage collection manually, by default JavaScript did those implementation for us. Other programming languages such as, C and C++ developer must implement those process manually.

Q: What is Garbage Collection?

Garbage Collection is a process of automatic memory management, on runtime automatically clear unused memory.

JavaScript is a Garbage Collected programming language, which means we don't need to worry about garbage cleanup. Javascript used Mark-and-Sweep algorithm which takes care of garbage collection and clealing.

Mark-and-Sweep: Garbage Collection Algorithm

Q: Interpretation vs Compilation vs JIT?

Interpretation: Interpreters run through a program line by line top to bottom, generating macing code and execute each command.

Issue: Initially code run fast but when code getting larger program will run slow.

Compilation: After writing code then compile entire source code to machine code at once, after that it generates a executable file example: install.exe than can be run by machine.

Issue: Initially process slow but execute fast.

Just-In-Time Compiled Language: Instantly translate source code to bytecode, than there is a feature called profiler which actually compile few code and return optimized code and finally adjusted with bytecode, this is a continuous process.

In the beginning JavaScript was Interpreted language, now modern JavaScript is JIT Compiled language. When Google map getting slower they introduce JIT method

Q: How JavaScript Engine Works?

যখন আমরা code লিখি সেটা browser এ গিয়ে parse/read হয়ে Abstract Syntax Tree তৈরি করে compiler এর সুবিধার জন্য। আমরা যে syntax error খাই সেটা এখান থেকেই আসে। মজার বেপার হল DOM এর সাথে AST এর কোনো সম্পর্ক নেই । তারপর Just-In-Time compilation হয়, শুরুতে interpretation mode এ compile হয় byte code তৈরি করে যেটা machine বুজতে পারে এবং execute করে পরবর্তিতে profiler এর মাধ্যমে কিছু code optimize করে bytecode এর সাথে adjust হয়। এই execution process টা আবার call stack এর মধ্যে হয় সেখানে memory heap এর মধ্যে memory allocation হয়, আর এই execution এর পাশাপাশি profiler কোডকে continuously আরও optimize করতে থাকে।

How V8 JavaScript engine works step by step (with diagram) - medium.com

Q: How JavaScript Runtime Works?

Runtime is a environment for run JavaScript Engine. JavaScript single-threaded কিন্তু একাধিক task acynchronously execute করতে পারে run time এর সাহায্যে, run time আমাদের web API provide করে যেটাকে helping hand ও বলা হয়, such as DOM, Timers, Fetch API. Web API এর মাধ্যমে যে task করা হয় সেগুলো callback queue তে জমা হয়, তখন event loop continuously check করে stack খালি আছে কিনা, তারপর সেখানে task execute হবার জন্য পাঠানো হয়। Node.js এর বেলায় processor এর main thread গুলো helping hand হিসাবে কাজ করে।

Q: What is Heap Memory? It is used to store objects and functions in JavaScript. The engine doesn’t allocate a fixed amount of memory. Instead, it allocates more space as required.

Q: What is Call Stack?

A call stack is a data structure that uses the Last In, First Out (LIFO) principle to temporarily store and manage function invocation (call). Call stack behaves like synchronous.

When we say that the call stack, operates by the data structure principle of Last In, First Out, it means that the last function that gets pushed into the stack is the first to be pop out, when the function returns.

Q: What is Garbage Collection?

Garbage collection is basically a process of managing memory automatically. Javascript uses Mark and Sweep algorithm.

Q: What is Memory Leak?

When allocated heap memory size exceep then causes meory leak.

Q: What Causes Memory Leak?

  1. Declaring global variable: Garbage collector global variable clean করবে না, কারণ global execution এর সময় global variable call হয় এবং memory allocation হয়, তখন garbage collector বুঝতে পারে না কোনটা clear করতে হবে
  2. Adding event listener without removing it.
  3. Setting timer without removing it.

Q: What is Event Loop? The event loop is the secret behind JavaScript’s asynchronous programming. JavaScript executes all operations on a single thread, but using a few smart data structures, it gives us the illusion of multi-threading.

const image = document.getElementById("img");
image.src = "user.jpg";

image.addEventListener("load", () => (
  image.classList.add("fade-in");
));

fetch("https:server.com/user/01")
.then((res) => console.log(res));
  • JavaScript uses async method for set "src".
- console.log(res) // Microtask Queue
- then()
- load data // inside web API's
- fetch()
- classList.add() // wait at call back queue
- addEventListener("load") // bind with load image
- load image // inside web API's
- getElementById()
- Global Execution
  • Promise related task are stack at Microtask queue
  • Microtask queue priority higher than Callback queue
  • Event Loop continuously check Microtask Queue, if exist than pause Callback queue execution and execute Microtask queue
  • setTimeout function execute after Callback queue, which means queue function's duration will be added with actual duration

Q: How JavaScript Execution Context works?

OR

How JavaScript Works? and How the code is executed?

Types of Execution Context :-

  1. Global Execution Context: Initially create context when load and provide us window object + this keyword
  2. Function Execution Context: After calling a function create context

Everything in JavaScript happens inside the Execution Context. There are two phases, one is a Creation Phase and other is a Execution Phase.

In Creation phase 3 things happened, first it creates a global or window object, second step is setup memory heap for storing variable and references functions, that means it takes all the variables and functions and store it in this window object, and third step is initializing those variable declarations with undefined and for function declaration it will store the whole function body. This is exact reason why hoisting occurs.

**Code**
let a = 10;

function multiply(x) {
  return x * 10;
}

let b = multiply(a);

console.log(b)
**Creation phase**
// 1st step: creating a global or window object
{}

// 2nd step: setup memory heap for storing variable and function
a;
multiply();
b;

// 3rd step: initializing those variable (hoisting)
a = undefined;
multiply(){...};
b = undefined;

During the execution phase, JavaScript engine execute codes line by line, assigning the values to variables and executes function calls. In this process JavaScript follows Single-Threaded Architecture. This means JavaScript can do one single task at a time in a specific order.

**Execution Phase**
// Assigning values to variables and execute function calls.
a = 10;
b = 100;
// 100

Q: What is Hoisting?

During the creation phrase javascript engine moves variables and function declarations (declare a function with fuction keyword) top of the code this is known as hoisting.

console.log(count); // undefined
var count = 1;

If we declared count variable using var keyword and if try to console.log() it before declared, we will get undefined.

console.log(count); // Reference Error: cannot access count before initialization.
let count = 1;

What if we try with let keyword javascript engine throw error that we cannot access variable before initialization, but variable declared with let keyword also hoisted but inside a temporal death zone. Temporal death zone is the time between declaration and initialization of let and const variables.

let x; // declaration
x = 50; // initialization

If write a function with function keyword then full function body hoisted. But function expression, arrow function & IIFE function are not hoisted.

// var test = undefined (Hoisted)
test()
var test = () {
  console.log("test"); // Typerrror: test is not a function
}

Example:

function abc() {
  console.log(a,b,c);
  const c = 30; // cannot access before init
  let b = 20; // cannot access before init
  var a = 10; // undefined
}

Here, variable declared with const and let are hoisted in temporal death zone. The both are initialized in the temporal death zone with undefined, also they are in the scope but not declared yet. So we cannot access them before initialization with actual value.

Q: What is Scope?

In computer programming scope determines the accessibility of variables, objects and functions from different part of the code.

In JavaScript there are three types of scope:

  1. Global Scope - accessible from anywhere
let x = 10;
function test(){
  return x; // here global scope accessed from a function
}
test();
  1. Function Scope - variables declared within a function can only be accessed within that function
function test(){
  let x = 10;
  console.log(x); // returns 10;
}
test();
console.log(x) // x is only accessible within it function
  1. Block Scope - variables declared within curly brackets{} cannot be accessed from outside
let age = 17; // global scope
if (age < 18){
  let drink = "juice"; // block scope
  console.log(drink);
} else {
  let drink = "water"; // block scope
  console.log(drink)
}
  • var has function scope.
    • It means they are only available inside the function they're created in, or if not created inside a function, they are globally scoped.
function test(){
  var x = 10;
}
test();
console.log(x) // ❌ NOT accessible outside of a function scope
  • let and const has block scope.

Q: What is Variable Shadowing? How to avoid Variable Shadowing?

When we declare variable using same name on outer scope and inner scope then inner scope value overlap with outer scope value. In that case we cannot access outer scope

Suppose, we declare variable using same name on outer scope and inner scope then we want to access outer scope value from inner scope but inner value will overlapping with outer scope this is called variable shadowing.

function test() {
  let a = "Hello"; // Outer Scope

  if (true) {
    let a = "Hi"; // Inner Scope
    console.log(a);
  }
  console.log(a);
}

test();
/* 
Hi
Hello
*/

To avoid this issue we have to declare variable using different name.

Q: What is Illegal Variable Shadowing?

When we declare same variable on outer scope using var and inner scope using let keyword it will causes variable shadowing but it is legal.

But when we declare same variable on outer scope using let and inner scope with var it will throw error like: SyntaxError: Identifier 'b' has already been declared. This kind of variable shadowing is illegal.

function test() {
  var a = "Hello";
  let b = "bye";

  if (true) {
    let a = "Hi";
    var b = "GoodBye";
    console.log(a);
    console.log(b);
  }
}
test();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment