JavaScript Interview Questions

JavaScript Interview Questions

javascript2Binterview2Bquestions
 

1. What are the data types available in JavaScript?

Boolean
Pretty standard across all languages, booleans are true and false. They’re often used for conditional statements.

Null and Undefined

Number
var num = 1; typeof num; // number
var num = 0.3; typeof num; // number

String

Symbol

var dog = { bark: true }

for (var property in dog) {
  if (dog.hasOwnProperty(property)) {
    console.log(property); // logs "bark"
  }
}

Since symbols are not enumerable they cannot be accessed in this way. However, the symbolised properties are not truly private since they can be accessed directly.

var breed = Symbol("breed");
var dog = { bark: true };
dog[breed] = "Corgi";
for (var property in dog) {
  if (dog.hasOwnProperty(property)) {
    console.log(property); // logs "bark", but not "breed"
  }
}
console.log(dog[breed]); // logs "Corgi"

Object
Everything in JS that we didn’t discuss above is an Object. So objects are the most complex data type; I’ll dedicate a future post to them since it’s a lot to cover here. But you’ve probably worked with objects in the past. They typically look like this:

var cat = { sound: "meow" };

var fluffy = new Cat();

var whiskers = new function() {
    this.sound = "meow";
}

2. In how many ways we can check for an Array in JavaScript?

We can check for an array in four ways as below:

return Array.isArray(obj);
return obj instanceof Array;
return Object.prototype.toString.call(obj) == "[object Array]";
return value && typeof value === 'object' && value.constructor === Array;
 

3. In how many ways you can create an object in JavaScript?

With new Object()

var person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";

With Json

var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}

var x = person;
x.age = 10;

With function

var car = function(t, d) {
 this.type = t;
 this.doors = d;
 this.enterCar = function() {
  console.log("Inside Car"); 
 }
};
//Creating an object of this function
var audi = new car('sedan', 2);
var newPerson=function(name){  
    var result = new Object();  
    result.name = name;  
    result.getName = function(){  
        return this.name;  
    };  
    return result;  
};  
var personOne = newPerson("Diego");  
var personTwo = newPerson("Gangelo");

With Prototype

function Person(name){  
        this.name = name;  
};  
Person.prototype.getName = function(){  
            return this.name;  
        };  
var personOne = new Person("Diego");  
var personTwo = new Person("Filippo");  
console.log(personOne.getName()); // prints Diego  
console.log(personTwo.getName()); // prints Filippo  
console.log(personOne.getName === personTwo.getName) //prints true

4. What is the difference between the operators ‘==‘ & ‘===‘?

The main difference between “==” and “===” operator is that formerly compares variable by making type correction e.g. if you compare a number with a string with numeric literal, == allows that, but === doesn’t allow that, because it not only checks the value but also type of two variable, if two variables are not of the same type “===” return false, while “==” return true.

5. What is the difference between null & undefined?

Undefined means a variable has been declared but has not yet been assigned a value. On the other hand, null is an assignment value. It can be assigned to a variable as a representation of no value. Also, undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.

6. What is the difference between undeclared & undefined?

Undeclared variables are those that do not exist in a program and are not declared. If the program tries to read the value of an undeclared variable, then a runtime error is encountered. Undefined variables are those that are declared in the program but have not been given any value. If the program tries to read the value of an undefined variable, an undefined value is returned.

7. What is the difference between ( for… in ) and ( for… of ) statements in JavaScript?

for…of in JavaScript

for of (new in ES6) does use an object-specific iterator and loops over the values generated by that.

Use for…of to iterate over the values in an iterable, like an array for example:

let animals = ['🐔', '🐷', '🐑', '🐇'];
let names = ['Gertrude', 'Henry', 'Melvin', 'Billy Bob'];

for (let animal of animals) {
  // Random name for our animal
  let nameIdx = Math.floor(Math.random() * names.length);

  console.log(`${names[nameIdx]} the ${animal}`);
}

// Henry the 🐔
// Melvin the 🐷
// Henry the 🐑
// Billy Bob the 🐇
Strings are also an iterable type, so you can use for…of on strings:

for in loops over enumerable property names of an object.

let str = 'abcde';

for (let char of str) {
  console.log(char.toUpperCase().repeat(3));
}

// AAA
// BBB
// …
You can also iterate over maps, sets, generators, DOM node collections and the arguments object available inside a functions.

for…in in JavaScript

Use for…in to iterate over the properties of an object (the object keys):
let oldCar = {
  make: 'Toyota',
  model: 'Tercel',
  year: '1996'
};

for (let key in oldCar) {
  console.log(`${key} --> ${oldCar[key]}`);
}

Output
// make –> Toyota
// model –> Tercel
You can also use for…in to iterate over the index values of an iterable like an array or a string:

let str = 'Turn the page';

for (let index in str) {
  console.log(`Index of ${str[index]}: ${index}`);
}

Output
// Index of T: 0
// Index of u: 1

8. What is Closure in JavaScript?

Closures are functions that refer to independent (free) variables. In other words, the function defined in the closure ‘remembers’ the environment in which it was created. Note: Free variables are variables that are neither locally declared nor passed as parameter.
Closure = function + outer function variables or context
function numberGenerator() {
  // Local “free” variable that ends up within the closure
  var num = 1;
  function checkNumber() {  // this is closer
num++;
    console.log(num);
  }
  return checkNumber;
}

var number = numberGenerator();
number(); // 2
number(); // 3

9. What’s the difference between let and var?

• A variable defined using a var statement is known throughout the function it is defined in, from the moment it is defined onward.
• A variable defined using a let statement is only known in the block it is defined in, from the moment it is defined onward.
To understand the difference, consider the following code:

function loop(arr) {
    // i IS NOT known here
    // j IS NOT known here

    for( var i = 0; i < arr.length; i++ ) {
        // i IS known here
    }

    // i IS known here
    // j IS NOT known here

    for( let j = 0; j < arr.length; j++ ) {
        // j IS known here
    }

    // i IS known here
    // j IS NOT known here
}

10. What is a generator?

A generator is a special type of function that during its execution it can be paused, yield results back the caller and resume later, at caller’s convenience. And this can happen as long as the generator has something to return, some value to yield back.

function* idMaker() {
  var index = 0;
  while (index < index+1)
    yield index++;
}

var gen = idMaker();

console.log(gen.next().value); // 0
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3

11. What is Mixins?

In JavaScript we can only inherit from a single object. There can be only one [[Prototype]] for an object. And a class may extend only one other class.

But sometimes that feels limiting. For instance, we have a class StreetSweeper and a class Bicycle, and want to make their mix: a StreetSweepingBicycle.

As defined in Wikipedia, a mixin is a class containing methods that can be used by other classes without a need to inherit from it.

// mixin
let sayHiMixin = {
  sayHi() {
    alert(`Hello ${this.name}`);
  },
  sayBye() {
    alert(`Bye ${this.name}`);
  }
};

// usage:
class User {
  constructor(name) {
    this.name = name;
  }
}

// copy the methods
Object.assign(User.prototype, sayHiMixin);

// now User can say hi
new User("Dude").sayHi(); // Hello Dude!

12. What is TypeScript? Why should we use it?

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript which runs on any browser or JavaScript engine.
TypeScript offers support for the latest JavaScript features and also has some additional features like static typing, object oriented programming and automatic assignment of constructor.

13. What is difference between JavaScript and TypeScript?

Typescript is a free and open-source programming language which is designed and developed by Microsoft. It was designed by Anders Hejlsberg at Microsoft. Typescript is a superset of JavaScript which primarily provides optional static typing, classes and interfaces. Typescript is compiled to provide clean and simple JavaScript code which runs on any browser. It allows JavaScript developers for using highly productive development tools and practices like static checking and code refactoring.
Differences between Typescript and JavaScript are

JavaScript don’t support Es6 while Typescript supports .
JavaScript build up reusable components by using unctions and prototype-based inheritance while Typescript supports Classes that allow programmer to think in more object oriented way .
JavaScript don’t have any interfaces while Typescript has interfaces.
There is no static typing in JavaScript whereas there is static typing in Typescript.
JavaScript has no optional parameter  feature while Typescript has optional parameter feature.

14. What are all the other access modifiers that TypeScript supports?

TypeScript supports access modifiers public, private and protected which determine the accessibility of a class member as given below:
public – All the members of the class, its child classes, and the instance of the class can access.
protected – All the members of the class and its child classes can access them. But the instance of the class can not access.
private – Only the members of the class can access them.
If an access modifier is not specified it is implicitly public as that matches the convenient nature of JavaScript.
Also note that at runtime (in the generated JS) these have no significance but will give you compile time errors if you use them incorrectly.

15. Explain Relative vs. Non-relative module imports.

Module imports are resolved differently based on whether the module reference is relative or non-relative.
A relative import is one that starts with /, ./ or ../. Some examples include:
import Entry from “./components/Entry”;
import { DefaultHeaders } from “../constants/http”;
Any other import is considered non-relative. Some examples include:
import * as $ from “jquery”;
import { Component } from “@angular/core”;
A relative import is resolved relative to the importing file and cannot resolve to an ambient module declaration. We should use relative imports for our own modules that are guaranteed to maintain their relative location at runtime.
A non-relative import can be resolved relative to baseUrl, or through path mapping.