JavaScript Interview Questions and Coding Problems - Part 1

Photo by Growtika on Unsplash

JavaScript Interview Questions and Coding Problems - Part 1

Write a JavaScript function to check whether given an input is an array or not.

  1. There are two ways :

    1) Array.isArray()

     function checkArray(input){
         return Array.isArray(input);
     }
    
     console.log(1);    // false
     console.log([]);    // true
     console.log([1, 2, 3]);     // true
    

    2) instanceof :

     function checkArray(input){
         return input instanceof Array;
     }
     console.log(1);    // false
     console.log([]);    // true
     console.log([1, 2, 3]);     // true
    
     /*
     When you create an array, it creates a new array object using Array constructor 
     that inherits properties and methods from the "Array.prototype".
     */
    

In how many ways we can clone an array?

There are several methods to clone an array

  1. slice()
let originalArray = [1, 2, 3];
let cloneArray = originalArray.slice();
  1. concat()
let originalArray = [1, 2, 3];
let cloneArray = originalArray.concat();
  1. Array.from()
let originalArray = [1, 2, 3, 4];
let cloneObject = Array.from(originalArray);
  1. spread operator ('...')
const originalArray = [1, 2, 3];
const clonedArray = [...originalArray];
💡
All mentioned methods of cloning do Shallow Copy. Shallow Copy creates a new object or array with copied top-level elements,but nested elements are shared references not independent copies.

Write a simple JS program to join all elements of the following array into a string.

const arr = ["My", "name", "is", "array"];

const arr = ["My", "name", "is", "Harshal."];
let joinElements = arr.join(' ');

console.log(joinElements); // Output: My name is Harshal.
💡
When we don't provide any separator inside join method, by default it assumes as comma(',').

Possible ways to create an Object.

  1. Object literal method

     const myObj = {
         name : "Prajakta",
         age : 28
     }
    
  2. Object.create() method

     const myObj = Object.create(null);
    
     // add properties
     myObj.name = "Komal";
     myObj["marital status"] = "Married";
    
  3. function constructor method

     function createObj(username, age){
         this.username = username;
         this.age = age;  
     }
    
     const user = new createObj("Aaditya", 29);
     // Output: {username: "Aaditya", age: 29}
    
    💡
    Whenever we call any function with new keyword, it creates an empty object and then thiskeyword add values to that empty object.
  4. using class

     class CreateObj{
         constructor(){
             this.a = 12;
         }
         walk = function(){console.log("Hello")}
     }
     const obj = new CreateObj();
     console.log(obj);
     // Output: {a: 12, walk: [Function: walk]}
    

What is Higher Order Function ?

A higher order function is a concept in functional programming where a function accept other functions as an arguments and/or return function as an output.

Accepting functions as an arguments:

function printSum(value1, value2, callback){
    return callback(valu1,value2);
}

function sum(value1, value2){
    return value1 + value2;
}

const addition = printSum(5, 6, sum)
console.log(addition);

Returning function:

function sum(inp){
    return function(inp2){return inp + inp2};   
}
cnsole.log(sum(20)(30)); // Ouput: 50

What is the difference between var, let and const keyword?

  • var keyword has been present since early versions of JavaScript, while let and const were introduced in ECMAScript 6(ES6).

  • var keyword is used to declare variables with function scope or global scope if declared outside functions. The variable declared using var keyword inside a function, it can be accessible anywhere inside the function, including inside nested function of that function.

      // var declared outside function
      const message1 = "Global";
    
      function myFunction(){
          // var inside function
          var message = 'Hello';
          console.log(message);    // Output: Hello
      }
    
      myFunction();
      console.log(message1);    // Output: Global
      console.log(message);     // Error: message is not defined
    
  • let and const are like var but they limit the variable's scope to the block of code where they are defined. Variable declared with const keyword, cannot be changed after assignment.

  • When you declare a variable using var keyword in the global scope**(outside of any function)**, it does get added to the property of global object , which is window object in the case of browser.

  • let and const do not become the properties of the 'window' object unlike variable declared with var .


Explain call, apply and bind methods?

  1. call()

    The call method is used to invoke a function with a specific this context and optional arguments. As we know, when we call a function directly in the global scope, the value of this inside a function is refers to the window object.

    But when we invoke a function using call method, it allows you to set the this value explicitly, overriding the default value which is window object.

     const person1 = {
       fullName: function(city) {
         return `${this.firstName} ${this.lastName} ${this.city}`
       }
     };
    
     const person2 = {
       firstName: "Harshal",
       lastName: "Dongare"
     };
    
     // Using call to invoke person1's fullName method with person2's context
     const bio = person1.fullName.call(person2, "Thane");
     console.log(bio);     // Output: Harshal Dongare Thane
    
  2. apply()

    The apply() method is similar to the call method in that it is used to invoke a function with a specific this context and arguments individually. However apply method invoke a function with this context and array of arguments.

    Alsoapply()method spreads the array of arguments so you don't need to use index to access the elements inside an array inside the called function.

     const person1 = {
       fullName: function(city) {
         return `${this.firstName} ${this.lastName} ${city}`
       }
     };
    
     const person2 = {
       firstName: "Harshal",
       lastName: "Dongare"
     };
    
     // Using call to invoke person1's fullName method with person2's context
     const bio = person1.fullName.apply(person2, ["Thane"]);
     console.log(bio);     // Output: Harshal Dongare Thane
    
  3. bind()

    The bind() method also does something similar to call() and apply() method but there are few things differently.

    The bind() method returns a new function with the specified this value and optional arguments but It does not immediately execute the function.

    bind() method takes arguments individually, similar to the call() method.

     const person1 = {
       fullName: function(city) {
         return `${this.firstName} ${this.lastName} ${city}`
       }
     };
    
     const person2 = {
       firstName: "Harshal",
       lastName: "Dongare"
     };
    
     // Using call to invoke person1's fullName method with person2's context
     const bio = person1.fullName.bind(person2, "Thane");
     console.log(bio());     // Output: Harshal Dongare Thane
    

⭐ what is the value of 'this' in different context ?

  • In the global scope of browser, the value of this refers to the window object.

  • In the browser, the value of this inside a regular function or an arrow function when called directly in the global scope, returns the window object.

      // Regular function
      function regularFunction() {
        console.log(this);
      }
    
      regularFunction(); // Logs: Window object (global scope)
    
      // Arrow function
      const arrowFunction = () => {
        console.log(this);
      };
    
      arrowFunction(); // Logs: Window object (global scope)
    
  • The value of this inside an object method refers to the object itself.

      const myObject = {
        property: 'value',
        myMethod() {
          console.log(this);
        }
      };
      myObject.myMethod(); // Output: {property: 'value', myMethod: ƒ}