Join Regular Classroom : Visit ClassroomTech

JavaScript Interview Questions – Intermediate Level | Codewindow.in

1. What is Hoisting in JavaScript?

/*Example 01: Variable Hoisting*/
console.log(message); // output : undefined
var message = "The variable Has been hoisted";
/*The above code looks like as below to the interpreter,*/
var message;
console.log(message);
message = "The variable Has been hoisted";
/*Example 02: Function Hoisting*/
function hoist() {
  a = 20;
  var b = 100;
}
hoist();
console.log(a);
/* 
Accessible as a global variable outside hoist() function
Output: 20
*/
console.log(b);
/*
Since it was declared, it is confined to the hoist() function scope.
We can't print it out outside the confines of the hoist() function.
Output: ReferenceError: b is not defined
*/
/*
All declarations (function, var, let, const and class) are hoisted in JavaScript, 
while the var declarations are initialized with undefined, but let and const declarations 
remain uninitialized.
*/
console.log(a);
let a = 3;
// Output: ReferenceError: a is not defined

They will only get initialized when their lexical binding (assignment) is evaluated during runtime by the JavaScript engine. This means we can’t access the variable before the engine evaluates its value at the place it was declared in the source code. This is what we call Temporal Dead Zone, A time span between variable creation and its initialization where they can’t be accessed.
Note: JavaScript only hoists declarations, not initialisation

2. What are closures?

A closure is the combination of a function and the lexical environment within which that function was declared. i.e, It is an inner function that has access to the outer or enclosing function’s variables. The closure has three scope chains
Own scope where variables defined between its curly brackets
Outer function’s variables
Global variables

function Welcome(name) {
  var greetingInfo = function(message) {
    console.log(message+' '+name);
  }
  return greetingInfo;
}
var myFunction = Welcome('John');
myFunction('Welcome '); // Output: Welcome John
myFunction('Hello Mr.'); // output: Hello Mr.John

/* As per the above code, the inner function greetingInfo() has 
access to the variables in the outer function Welcome() even 
after outer function has returned. */

3. What is an event flow?

Event flow is the order in which event is received on the web page. When you click an element that is nested in various other elements, before your click actually reaches its destination, or target element, it must trigger the click event each of its parent elements first, starting at the top with the global window object.
There are two ways of event flow
Top to Bottom(Event Capturing)
Bottom to Top (Event Bubbling)

4. What is the difference between Call, Apply and Bind?

call(): The call() method invokes a function with a given this value and arguments provided one by one

var employee1 = {firstName: 'John', lastName: 'Rodson'};
var employee2 = {firstName: 'Jimmy', lastName: 'Baily'};
function invite(greeting1, greeting2) {
    console.log(greeting1 + ' ' + this.firstName + ' ' + this.lastName+ ', '+ greeting2);
}
invite.call(employee1, 'Hello', 'How are you?'); // Hello John Rodson, How are you?
invite.call(employee2, 'Hello', 'How are you?'); // Hello Jimmy Baily, How are you?
apply(): Invokes the function and allows you to pass in arguments as an array
var employee1 = {firstName: 'John', lastName: 'Rodson'};
var employee2 = {firstName: 'Jimmy', lastName: 'Baily'};
function invite(greeting1, greeting2) {
    console.log(greeting1 + ' ' + this.firstName + ' ' + this.lastName+ ', '+ greeting2);
}
invite.apply(employee1, ['Hello', 'How are you?']); // Hello John Rodson, How are you?
invite.apply(employee2, ['Hello', 'How are you?']); // Hello Jimmy Baily, How are you?
bind(): returns a new function, allowing you to pass in an array and any number of arguments
var employee1 = {firstName: 'John', lastName: 'Rodson'};
var employee2 = {firstName: 'Jimmy', lastName: 'Baily'};
function invite(greeting1, greeting2) {
    console.log(greeting1 + ' ' + this.firstName + ' ' + this.lastName+ ', '+ greeting2);
}
var inviteEmployee1 = invite.bind(employee1);
var inviteEmployee2 = invite.bind(employee2);
inviteEmployee1('Hello', 'How are you?'); // Hello John Rodson, How are you?
inviteEmployee2('Hello', 'How are you?'); // Hello Jimmy Baily, How are you?

5. How do you validate an email in javaScript?

You can validate an email in javascript using regular expressions. It is recommended to do validations on the server side instead client side. Because the javascript can be disabled on the client side.

function validateEmail(email) {
    var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(String(email).toLowerCase());
}

C QA

Mostly Asked

DS QA

Mostly Asked

DBMS QA

Mostly Asked

ML QA

Mostly Asked

6. What is the purpose of compareFunction while sorting arrays?

The compareFunction is used to define the sort order. If omitted, the array elements are converted to strings, then sorted according to each character’s Unicode code point value. Let us take an example to see the usage of compareFunction,

let numbers = [1, 2, 5, 3, 4];
numbers.sort((a, b) => b - a);
console.log(numbers); // [5, 4, 3, 2, 1]

7. How do you find min and max value in an array?

You can use Math.min and Math.max methods on array variable to find the minimum and maximum elements with in an array. Let us create two functions to find the min and max value with in an array.

var marks = [50, 20, 70, 60, 45, 30];
function findMin(arr) {
  return Math.min.apply(null, arr);
}
function findMax(arr) {
  return Math.max.apply(null, arr);
}
console.log(findMin(marks));
console.log(findMax(marks));

8. What is a typical use case for anonymous functions?

They can be used in IIFEs to encapsulate some code within a local scope so that variables declared in it do not leak to the global scope.

(function() {
  // Some code here.
})();
/*
As a callback that is used once and
does not need to be used anywhere else. The code will seem more self-contained and 
readable when handlers are defined right inside the 
code calling them, rather than having to search elsewhere
to find the function body.
*/
setTimeout(function() {
  console.log('Hello world!');
}, 1000);

/*Arguments to functional programming constructs or Lodash (similar to callbacks). */

const arr = [1, 2, 3];
const double = arr.map(function(el) {
  return el * 2;
});
console.log(double); // [2, 4, 6]

9. Difference between: function Person(){}, var person = Person(), and var person = new Person()?

This question is pretty vague. My best guess at its intention is that it is asking about constructors in JavaScript. Technically speaking, function Person(){} is just a normal function declaration. The convention is to use PascalCase for functions that are intended to be used as constructors.

var person = Person() invokes the Person as a function, and not as a constructor. Invoking as such is a common mistake if the function is intended to be used as a constructor. Typically, the constructor does not return anything, hence invoking the constructor like a normal function will return undefined and that gets assigned to the variable intended as the instance.

var person = new Person() 
/*
creates an instance of the Person object using the new operator, which inherits from Person.prototype. 
An alternative would be to use Object.create, such as: Object.create(Person.prototype).
*/
function Person(name) {
  this.name = name;
}
var person = Person('John');
console.log(person); // undefined
console.log(person.name); // Uncaught TypeError: Cannot read property 'name' of undefined
var person = new Person('John');
console.log(person); // Person { name: "John" }
console.log(person.name); // "john"

10. What is the difference between .call and .apply?

Both .call and .apply are used to invoke functions and the first parameter will be used as the value of this within the function. However, .call takes in comma-separated arguments as the next arguments while .apply takes in an array of arguments as the next argument. An easy way to remember this is C for call and comma-separated and A for apply and an array of arguments.

function add(a, b) {
  return a + b;
}
console.log(add.call(null, 1, 2)); // 3
console.log(add.apply(null, [1, 2])); // 3

11. What is the difference between an “attribute” and a “property”?

Attributes are defined on the HTML markup but properties are defined on the DOM. To illustrate the difference, imagine we have this text field in our HTML:

<input type="text" value="Hello">
const input = document.querySelector('input');
console.log(input.getAttribute('value')); // Hello
console.log(input.value); // Hello

// But after you change the value of the text field by adding "World!" to it, this becomes:

console.log(input.getAttribute('value')); // Hello
console.log(input.value); // Hello World!

12. How can you achieve immutability in your own code?

One way to achieve immutability is to use libraries like immutable.js, mori or immer.

The alternative is to use const declarations combined with the techniques mentioned above for creation. For “mutating” objects, use the spread operator, Object.assign, Array.concat(), etc., to create new objects instead of mutate the original object.

Examples:
// Array Example
const arr = [1, 2, 3];
const newArr = [...arr, 4]; // [1, 2, 3, 4]
// Object Example
const human = Object.freeze({race: 'human'});
const john = { ...human, name: 'John' }; // {race: "human", name: "John"}
const alienJohn = { ...john, race: 'alien' }; // {race: "alien", name: "John"}

13. Explain the differences on the usage of foo between function foo() {} and var foo = function() {}?

The former is a function declaration while the latter is a function expression. The key difference is that function declarations have its body hoisted but the bodies of function expressions are not (they have the same hoisting behavior as variables). For more explanation on hoisting, refer to the question above on hoisting. If you try to invoke a function expression before it is defined, you will get an Uncaught TypeError: XXX is not a function error.

// Function Declaration
foo(); // 'FOOOOO'
function foo() {
  console.log('FOOOOO');
}
// Function Expression
foo(); // Uncaught TypeError: foo is not a function
var foo = function() {
  console.log('FOOOOO');
};

14. What are the differences between variables created using let, var or const?

Variables declared using the var keyword are scoped to the function in which they are created, or if created outside of any function, to the global object. let and const are block scoped, meaning they are only accessible within the nearest set of curly braces (function, if-else block, or for-loop).

function foo() {
  // All variables are accessible within functions.
  var bar = 'bar';
  let baz = 'baz';
  const qux = 'qux';
  console.log(bar); // bar
  console.log(baz); // baz
  console.log(qux); // qux
}
console.log(bar); // ReferenceError: bar is not defined
console.log(baz); // ReferenceError: baz is not defined
console.log(qux); // ReferenceError: qux is not defined
if (true) {
  var bar = 'bar';
  let baz = 'baz';
  const qux = 'qux';
}
// var declared variables are accessible anywhere in the function scope.
console.log(bar); // bar
// let and const defined variables are not accessible outside of the block they were defined in.
console.log(baz); // ReferenceError: baz is not defined
console.log(qux); // ReferenceError: qux is not defined

/* 
var allows variables to be hoisted, meaning they can be referenced in code before they are declared. let and const will not allow this, instead throwing an error.
*/

console.log(foo); // undefined
var foo = 'foo';
console.log(baz); // ReferenceError: can't access lexical declaration 'baz' before initialization
let baz = 'baz';
console.log(bar); // ReferenceError: can't access lexical declaration 'bar' before initialization
const bar = 'bar';

/*
Redeclaring a variable with var will not throw an error, but 'let' and 'const' will.
*/

var foo = 'foo';
var foo = 'bar';
console.log(foo); // "bar"
let baz = 'baz';
let baz = 'qux'; // Uncaught SyntaxError: Identifier 'baz' has already been declared

/*
let and const differ in that let allows reassigning the variable's value while const does not.
*/

// This is fine.
let foo = 'foo';
foo = 'bar';
// This causes an exception.
const baz = 'baz';
baz = 'qux';

15. How can you share code between files?

This depends on the JavaScript environment.
On the client (browser environment), as long as the variables/functions are declared in the global scope (window), all scripts can refer to them. Alternatively, adopt the Asynchronous Module Definition (AMD) via RequireJS for a more modular approach.
On the server (Node.js), the common way has been to use CommonJS. Each file is treated as a module and it can export variables and functions by attaching them to the module.exports object.
ES2015 defines a module syntax which aims to replace both AMD and CommonJS. This will eventually be supported in both browser and Node environments.

console.log('location.href', window.location.href); // Returns full URL

16. What is the difference between typeof and instanceof?

typeof is an operator that returns a string with the type of whatever you pass.
The typeof operator checks if a value belongs to one of the seven basic types: number, string, boolean, object, function, undefined or Symbol.
typeof(null) will return object.
instanceof is much more intelligent: it works on the level of prototypes. In particular, it tests to see if the right operand appears anywhere in the prototype chain of the left. instanceof doesn’t work with primitive types. It instanceof operator checks the current object and returns true if the object is of the specified type, for example:

var dog = new Animal();
dog instanceof Animal; // Output : true

/*
Here dog instanceof Animal is true since dog inherits from Animal.prototype
*/

var name = new String("xyz");
name instanceof String; // Output : true
Categories
Pages
Recent Posts