DEV Community

Cover image for Common JavaScript interview questions
Charles Cee Jay
Charles Cee Jay

Posted on

Common JavaScript interview questions

Today, we're going to discuss and answer common JavaScript interview questions you'd encounter as a JavaScript developer. These include different well arranged and answered questions to get you prepared to attend your next interview with confidence. Let's dive right in!

What are the different data types present in JavaScript?

There are two major data types in javascript which are the primitive and non-primitive data types.
The primitive data types includes :

  • Strings : A string is a collection of alphanumeric characters. I start a string by typing double quotes, single quotes, or the backtick character. Double quote and single quote behave identically, and the backtick character comes with some extra functionality.

  • Boolean : Boolean has two values. True and false. When we create a boolean, we’re simply saying it’s true or it’s false.

  • Null : A variable has the data type of null when it is assigned to a zero or an empty string.

  • Undefined : When a variable is declared and assigned to nothing, it has the data type of undefined or when you try to access a variable that hasn't been declared.

The non-primitive data types includes:

  • Object: an object is a standalone entity, with properties and type. e.g
const obj = {
name : "cup",
quantity : 3,
color : "red",
sold : "true"
}
Enter fullscreen mode Exit fullscreen mode
  • Array : Array is a single variable that is used to store different elements. e.g
const arr = ["goat", "sheep", 2, 4, "rat"]
Enter fullscreen mode Exit fullscreen mode

Explain Hoisting in JavaScript

JavaScript Hoisting 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.

Difference between “==” and “===” operators

The "==" and the "===" are both used to compare values of variables, but while the "==" doesn't check for data type, the "===" checks for data type.
e.g

const num = 3
const foo = "3"
num == foo
// true
num === foo
// false
Enter fullscreen mode Exit fullscreen mode

Explain Implicit Type Coercion in JavaScript

JavaScript's implicit coercion simply refers to JavaScript attempting to force an unexpected value type to the expected type. So you can pass a string where it expects a number, an object where it expects a string etc, and it will try to convert it to the right type.
eg

const num = 3
const str = "3"
str + num 
// returns 33.This means that the num has been coerced from number type variable to a string and concatenated
Enter fullscreen mode Exit fullscreen mode

Is JavaScript a statically typed or a dynamically typed language?

JavaScript is dynamically typed which means the interpreter assigns variables a type at runtime based on the variable's value at the time.

What is NaN property in JavaScript?

In JavaScript, NaN is short for "Not-a-Number". In JavaScript, NaN is a number that is not a legal number. The Global NaN property is the same as the Number. Nan property.
e.g

const checkNumber =(x)=> {
  if (isNaN(x)) {
    return NaN;
  }
  return x;
}

console.log(checkNumber(1));
// expected output: "1"

console.log(checkNumber('NotANumber'));
// expected output: NaN
Enter fullscreen mode Exit fullscreen mode

Explain passed by value and passed by reference

"Passing by value" means that you pass the actual value of the variable into the function. While, "Passing by reference" means that you pass the variable itself into the function (not just the value).
e.g

let str1 = "Ada"
let str2 = "lovelace"
const fullName = (name1,name2) =>{
let name = name1.concat(name2)
console.log(name)

fullName(str1,str2)
//passed by reference
fullName ("Ada","lovelace")
//passed by value
Enter fullscreen mode Exit fullscreen mode

What is an Immediately Invoked Function in Javascript?

An Immediately-invoked Function Expression (IIFE for friends) is a way to execute functions immediately, as soon as they are created.

IIFEs are very useful because they don’t pollute the global object, and they are a simple way to isolate variables declarations.They are enclosed in parenthesis and are ended with parenthesis.
e.g

((name) => {
  console.log(name)
})()
Enter fullscreen mode Exit fullscreen mode

Explain Higher Order Functions in Javascript

Functions that operate on other functions, either by taking them as arguments or by returning them, are called higher-order functions. Higher-order functions allow us to abstract over actions, not just values. They come in several forms. For example, we can have functions that create new functions or one which can change other functions.

Explain “this” keyword

  “This” keyword refers to an object that is executing the current piece of code. It references the object that is executing the current function.A function's "this" keyword behaves a little differently in JavaScript compared to other languages.
Enter fullscreen mode Exit fullscreen mode

In the global execution context (outside of any function), "this" refers to the global object whether in strict mode or not.
Inside a function, the value of this depends on how the function is called.
If code is not in strict mode, and the value of "this" is not set by the call, this will default to the global object, which is window in a browser.

const score = {
  val: 342,
  display: function() {
    return this.prop;
  },
};

console.log(score.display());
Enter fullscreen mode Exit fullscreen mode

Explain call(), apply() and, bind() methods

The bind() method creates a new function that, when called, has its this keyword set to the provided value.

The call() method calls a function with a given this value and arguments provided individually.
The main difference of this with the former is that it :

  • Accepts additional parameters as well
  • Executes the function it was called upon right away.
  • The call() method does not make a copy of the function it is being called on.

The apply() method is just like the call() method but the difference is that the call() accepts arguments separated by comma while the apply accepts arguments as arrays.
e.g

let student = {
    firstname: 'John',
    lastname: 'green ',
    getStudentName: function() {
        let fullname = this.firstname + ' ' + this.lastname;
        return fullname;
    }
};

let studentFavourites = function(snack, hobby) {
    console.log(this.getStudentName() + ' loves ' + snack + ' and ' + hobby);
};

studentFavourites.call(student,'Junks', 'Fantasy'); // John Green loves Junks and Fantasy
studentFavourites.apply(student,['Junks', 'Fantasy']);// John Green loves Junks and Fantasy

Enter fullscreen mode Exit fullscreen mode

What is Currying in Javascript?

Currying is actually a process of linking functions together to reduce the number of arguments they take by utilizing lambda calculus. This technique gives us an option to control how arguments are passed to functions.
Currying is a functional programming technique which transforms a function that takes multiple arguments into a sequence of nesting functions that each take only a single argument.

function addNumber(x) {
  return function (y) {
    return function (z) {
      return x + y + z;
    };
  };
}

const add5 = addNumber(5);

const add10 = add5(10);

const add15 = add10(15);
console.log('Returns 30', add15);

Enter fullscreen mode Exit fullscreen mode

Explain Scope and Scope Chain in Javascript

Scope is the way of accessing variables, functions, and objects in some particular part of your code during runtime.
They are mainly two types :

Global Scope :
Variables defined outside a function are in the global scope. Also, There is only one Global scope throughout a JavaScript document.Once you’ve declared a global variable, you can use that variable anywhere in your code, even in function

local Scope :
Variables defined inside a function are in local scope.And they have a different scope for every call of that function. Also, Each function when invoked creates a new scope. So there is a Function scope also.
e.g

let str = "car"
// global var str
const func =()=>{
let rat = "mammal"
// local var rat
}
Enter fullscreen mode Exit fullscreen mode

** Scope Chain :** The scope chain is used to resolve the value of variable names in Javascript. Without a scope chain the Javascript engine wouldn't know which value to pick for a certain variable name if there are multiple defined at different scopes.

Explain Closures in JavaScript

In JavaScript, a closure is a function that references variables in the outer scope from its inner scope. The closure preserves the outer scope inside its inner scope.
  A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.
Enter fullscreen mode Exit fullscreen mode

What are object prototypes?

Prototype property is basically an object (also known as Prototype object), where we can attach methods and properties in a prototype object, which enables all the other objects to inherit these methods and properties.
Prototypes are the mechanism by which JavaScript objects inherit features from one another.
e.g

const personPrototype = {
  greet() {
    console.log(`hello, my name is ${this.name}!`);
  }
}

function Person(name) {
  this.name = name;
}

Person.prototype = personPrototype;
Person.prototype.constructor = Person;
Enter fullscreen mode Exit fullscreen mode

What are callbacks?

Any function that is passed as an argument to another function so that it can be executed in that other function is called as a callback function.

function myfunc(some) {
  // some blocks of code
}

function func2(param1, param2, Callback) {
  // some codes
}

func2(arg1,arg2, myfunc);
Enter fullscreen mode Exit fullscreen mode

What is memoization?

 Memoization is an optimization technique where expensive function calls are cached such that the result can be immediately returned the next time the function is called with the same arguments
Enter fullscreen mode Exit fullscreen mode

What is recursion in a programming language?

The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called as recursive function. Using recursive algorithm, certain problems can be solved quite easily

What is the use of a constructor function in javascript?

  A constructor is a special function that creates and initializes an object instance of a class. In JavaScript, a constructor gets called when an object is created using the new keyword. The purpose of a constructor is to create a new object and set values for any existing object properties.

The purpose of a constructor is to create an object and set values if there are any object properties present. It’s a neat way to create an object because you do not need to explicitly state what to return as the constructor function, by default, returns the object that gets created within it.
Enter fullscreen mode Exit fullscreen mode
function Car(name, colour) {
  this.name = name
  this.colour = colour
}


let car1 = new Car("Maybach", "Steel black")
console.log(car1)
var car2 = new Car("Venza", "Teal")
console.log(car2)

Enter fullscreen mode Exit fullscreen mode

What is DOM?

The Javascript DOM (Document Object Model) is an interface that allows developers to manipulate the content, structure and style of a website.
DOM contains a bunch of nodes where each node represents an HTML element. The tag always comes at the top and hence is called the “root node”. The rest of the nodes come under it and hence are called “children nodes”. The nodes present at the bottom are called “leaves” and are usually filled with elements’ attributes, values and events.

Well, I hope this really helps you get prepared to be interviewed for your next Job as a Javascript developer. Thanks for reading through.

Credits to different authors and tutorials I consulted.

Latest comments (0)