Most JavaScript Interview Question That You Should Need To Know

Asif Hasan Irfan
6 min readMay 8, 2021

1. Truthy And Falsy Values

When you write if/else a statement in any programming language, you expect to pass a value in the if() a condition that is strictly boolean which means either true or false.

  • If the number is 0, Then the condition is false. Otherwise, the condition is true.
  • If the string is empty, Then the condition is false. Otherwise, the condition is true.
  • If any variable has not a value, undefined, null, NaN, false, then the condition is false. Otherwise, the condition is true. These are as follows.
falsy  -> false, '', "", 0, -0, 0n, NaN, null, undefined
truthy -> anything that is not mentioned above

2. Difference Between “Null ” And “Undefined”

When you define a variable but not assign a value to it, it automatically puts a placeholder which is called undefined so you don’t have to do it manually, JavaScript does it for you.

Null means an empty or non-existent value.

Null is assigned and explicitly means nothing. while undefined typically means a variable has been declared but not defined yet.

var a;
console.log(a);
// undefined

var b = null;
console.log(b);
// null

As you can see so far, null and undefined are different, but share some similarities. Thus, it makes sense that null does not strictly equal undefined.

console.log(null !== undefined);
// true

But, and this may surprise you, null loosely equals undefined.

console.log(null == undefined);
// true

In JavaScript, a double equal means we compare two values after converting them to a common type.

3. Double (==) vs Triple (===) Equals

If you have a javaScript interview coming up soon, then ready to answer one of the most frequently asked questions: “What is the difference between using “==” and “===” operator?”

When using double equals in JavaScript we are testing for loose equality. It will compare two elements irrespective of their datatype. It also converts the variable values to the same type before performing a comparison. This is known as type coercion. On the other hand, the “===” operator is known as strict equality. This means both the type and the value we are comparing have to be the same.

4. Introduction To Scope and Block Scope

Scope determines the visibility or accessibility of a variable or other resource in the area of your code.

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 scopes.

//global scope
var fruit = 'apple'
console.log(fruit); //apple

function getFruit(){
console.log(fruit); //fruit is accessible here
}

getFruit(); //apple

Local Scope

Every function has its own scope. Variables which declared inside the functions become Local Scope to the function. The same variable can be used in different functions. Because they are bound to the respective functions and are not mutually visible.

//global scope
function foo1(){
//local scope 1
function foo2(){
//local scope 2
}
}

//global scope
function foo3(){
//local scope 3
}

Function Scope

When 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. 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

Lexical Scope

Lexical scope means the children's scope has the access to the variables defined in the parent scope. The children's functions are lexically bound to the execution context of their parents.

function foo1(){
var fruit1 = 'apple';
const fruit2 = 'banana';
let fruit3 = 'strawberry';
function foo2(){
console.log(fruit1);
console.log(fruit2);
console.log(fruit3);
}
foo2();
}

foo1();

//result:
//apple
//banana
//strawberry

5. Closure, Encapsulation, and Private Variable

=> Closure:-

Closure is one of the important concepts in JavaScript. It is a widely discussed and still confused concept. Let’s understand what the closure is.

A closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time. To use a closure, define a function inside another function and expose it. To expose a function, return it or pass it to another function.

function makeFunc() {
var name = 'Mozilla';
function displayName() {
alert(name);
}
return displayName; }
var myFunc = makeFunc();
myFunc();

=> Encapsulation:-

Encapsulation is one of the main concepts in object-oriented programming. It allows an object to groups both private and public members under a single name. All the object-oriented programming languages support this.

  • Use var keywords to make data members private.
  • Use setter methods to set the data and getter methods to get that data.

Let’s see a simple example of encapsulation that contains two data members with its setter and getter methods.

// Only works for arrays
const doubleAllImperative = data => {
const doubled = [];
for (let i = 0, length = data.length; i < length; i++) {
doubled[i] = data[i] * 2;
}
return doubled;
};// Same as above, but works for anything with the
// map operation.
const doubleAllInterface = data => data.map(x => x * 2);const box = value => ({
map: f => box(f(value)),
toString: () => `box(${ value })`
});console.log(
doubleAllInterface([2,3]), // [4, 6]
doubleAllInterface(box(2)).toString(), // box(4)
);

Private Variable:-

In many object-oriented programming languages, there is a way to limit the visibility of a variable from outside its scope. In other words, some programming languages allow variables to only be accessible by the object that “owns” it. To be more technical, a private variable is only visible to the current class. It is not accessible in the global scope or to any of its subclasses. For example, we can do this in Java (and most other programming languages) by using the private keyword when we declare a variable. Attempting to access the private variable outside of the class that owns it will throw an error.

// Example Class
class Example {
// hiddenVariable CAN only be accessed here
private String hiddenVariable;

public Example(String websiteName) {
hiddenVariable = websiteName;
}
}

// Main Method
public class Main {
public static void main(String[] args) {
// Instantiate class
Example website = new Example("DEV.to");

// This will throw an error
// error: hiddenVariable has private access in Example
System.out.println(website.hiddenVariable);
}
}

6. Difference Between bind, call, and apply

Today I’ll talk about the differences between bind vs. call vs. apply. These JavaScipt methods allow you to change the value of ‘this’ for a given function. Call and apply are interchangeable. You can decide whether it’s easier to send in an array or a comma-separated list of arguments. Bind is different. It always returns a new function.

Function.prototype.bind()

The Bind method returns a new function, allowing you to pass in this array and any number of arguments. use it when you want that function to later be called with a certain context like events.

let customer1 = { name: 'Leo', email: 'leo@gmail.com' };
let customer2 = { name: 'Nat', email: 'nat@hotmail.com' };function greeting(text) {
console.log(`${text} ${this.name}`);
}let helloLeo = greeting.bind(customer1);
let helloNat = greeting.bind(customer2);helloLeo('Hello'); // Hello Leo
helloNat('Hello'); // Hello Nat

Function.prototype.call()

The call method invokes the function and allows you to pass in arguments one by one using commas.

let customer1 = { name: 'Leo', email: 'leo@gmail.com' };
let customer2 = { name: 'Nat', email: 'nat@hotmail.com' };

function greeting(text) {
console.log(`${text} ${this.name}`);
}

greeting.call(customer1, 'Hello'); // Hello Leo
greeting.call(customer2, 'Hello'); // Hello Nat

Function.prototype.apply()

The apply method invokes the function and allows you to pass in arguments as an array.

let customer1 = { name: 'Leo', email: 'leo@gmail.com' };
let customer2 = { name: 'Nat', email: 'nat@hotmail.com' };function greeting(text, text2) {
console.log(`${text} ${this.name}, ${text2}`);
}greeting.apply(customer1, ['Hello', 'How are you?']); // output Hello Leo, How are you?
greeting.apply(customer2, ['Hello', 'How are you?']); // output Hello Natm How are you?

--

--

Asif Hasan Irfan

I'm a junior web developer. JavaScript is my favorite programming language. As a programmer, I love taking on challenges and love being part of the solution.