How To Crack Node.js Interview ?

Node.js popularity has been all time high and so is the need for good Node.js developers. I have been to some node.js/javascript interview’s and  I am writing this blog to share my experience.

So what interviewer is looking for a node.js person?

  • Javascript plays a key role in Node.js so you should be very well prepared on javascript. It is primarily used for doing server side programming. In a typical example calling a web service or doing I/O to and from a database.
  • Understanding of core Node.js concepts :  clustering, file system, async programming etc.
  • Understanding of Express.js concepts: Express is official node.js web framework so it very important to understand this well. Some of the area you should focus: Routing, Post & Get, Different type of response code in express, middleware etc.
  • Understanding of testing javascript in general. Eg: Mocha, Jasmine etc.

 

JavaScript:

Javascript was written in just 10 days in May 1995 by Brendan Eich. 10 days is quite short time for a programming language which is killing the industry right now. In 1996 – 1997 JavaScript was taken to ECMA to carve out a standard specification, which other browser vendors could then implement based on the work done at Netscape. JavaScript was historically known as language of the browser until Node.js was born. Then people start using it for server side too. So today full stack development in Javascript is possible.

This video from Douglas Crockford touches all the good parts for javaScript(if you are not already familiar).

What is inheritance model in javascript  ?

Inheritance is concept where child class can inherit the properties of parent’s class. There are two types of inheritance in javascript.

a) Prototypal inheritance (by use to prototype).

Demo | Source

Screen Shot 2016-03-13 at 8.15.57 PM

b) Differential inheritance (by use of Object.create()).

Demo | Source

Screen Shot 2016-03-13 at 8.21.21 PM

Read more on inheritance:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

http://www.crockford.com/javascript/inheritance.html

What is a closure?

Closure is concept in javascript where a function can return a function.The pattern of public, private, and privileged members is possible because JavaScript has closures.  What this means is Inner functions will always have access to var and parameters of outer function even after when outer function is returned.

Demo | Source

Screen Shot 2016-03-13 at 8.53.15 PM.png

What is hoisting ?

Hoisting is a JavaScript’s default behavior of moving declarations to the top function.

Demo| Source

Screen Shot 2016-03-13 at 10.17.53 PM

  What is the difference between Call vs Apply vs Bind ?

  • Call invokes the function and allows you to pass in arguments one by one.
  • Apply invokes the function and allows you to pass in arguments as an array.
  • Bind returns a new function, allowing you to pass in a this array and any number of arguments.

Demo| Source

var father = {
 age: 50,
 celebrateBirthday: function(fPrefix, fPostfix) {
 return fPrefix +this.age + fPostfix;
 }
};

var son = {
 age: 22
};

alert(father.celebrateBirthday('Dad is now: ', 'yr old'));//Dad is now: 51yr old

alert(father.celebrateBirthday.apply(son, ['Son is now: ', 'yr old']));//Son is now: 22yr old

alert(father.celebrateBirthday.call(son, 'Son is now: ', 'yr old'));//Son is now: 22yr old

alert(father.celebrateBirthday.bind(son)('Son is now: ', 'yr old'));//Son is now: 23yr old

 

What is type inference? can you explain  the difference between the == operator and the === operator?

Type inference is when the javascript interpreter tries to determine the type of a reference in the runtime. “==” performs type conversion before evaluating the comparison  and “===” is used for strict comparison (will return false if type of two values which are to compared does not match).

Source

Screen Shot 2016-03-13 at 10.51.55 PM

These are some basic javascript questions you can expect in technical interview.I have few more example on my github. I would recommend taking a look.

What is the use of “use strict” ?

  • Strict mode changes previously accepted “bad syntax” into real errors.
  • In normal JavaScript, mistyping a variable name creates a new global variable. In strict mode, this will throw an error, making it impossible to accidentally create a global variable.
  • In strict mode, any assignment to a non-writable property, a getter-only property, a non-existing property, a non-existing variable, or a non-existing object, will throw an error.

Few examples:

  • “use strict”;
    x = 2;                // This will cause an error (x is not defined)
  • “use strict”;
    function x(p1, p1) {};   // This will cause an error

What is the use of this keyword ?

This keyword is generally used to refer properties of an object that the function is bound to. This keyword is usually used inside a function. It can be used outside the function too in the global scope but its not recommended to use this in this way. In strict mode this refers to undefined.

Demo

Example:

function Person(name, age) {
 this.name = name;
 this.age = age;
 }
 //Create a prototype
 Person.prototype.sayHi = function() {
 console.log("Hi my name is " + this.name + " and I am " + this.age);
 }
 var steve = new Person("steve", 35);
 steve.sayHi(); //Hi my name is steve and I am 35

Does Javascript uses pass by value or pass by reference?

Javascript uses both. Arguments (for example function arguments) are passed by value. i.e if a function changes an argument’s value, it does not change it’s original value.

Objects are passed by reference. i.e If a function changes an object property, it changes the original value.

Pass by value:                                                                                                                                     Demo

var addDouble = function(a, b) {  
//change value of a and b.
  a = a * 2;//4
  b = b * 2;//6
  return x + y;
}
var a = 2, b = 3;
addDouble(a, b); 
//original value does not change
console.log(a);  // 2  
console.log(b);  // 3  

Pass by reference:    

Demo

var changeName = function(obj) { 
 obj.firstName = "Hitesh";
}
var obj = { 
 firstName: "Greg",
 lastName: "Clooney"};
//Before 
console.log(obj); //{firstName: "Greg", lastName: "Clooney"} 
changeName(obj); 
//After : pass by reference (changes original valye)
console.log(obj); //{firstName: "Hitesh", lastName: "Clooney"}

How to write a callback function?

This is very important concept for node.js. A callback is function which can be passed on to another function as an argument. At some point in time later in the call back function is executed.

Demo

function callbackDemo(firstName, callback){
 alert("My name is " + firstName );
 //Execute the callback after 3 secs
 setTimeout(function(){
 callback(firstName);
 }, 3000);
}

var welcome = function(name){
 alert('Welcome Mr. ' + name);
};

callbackDemo("Sam", welcome);

Express JS

Express is highly opinionated web application for Node.js application. Express is commonly used to creating an API layer for your application but it can also be used for rendering an html page. Many popular framework are built on express.

Read more about frameworks for Node.js.

Some questions you an expects on Express framework:

How can you create a route in express ?

Routing refers to the definition of application end points (URIs) and how they respond to client requests. Route are created in express using express.Router() module. Here is an example:

Screen Shot 2016-04-03 at 11.38.04 PM

Express supports the following routing methods that correspond to HTTP methods: get, post, put, head, delete, options, trace, copy, lock, mkcol, move, purge, propfind, proppatch, unlock, report, mkactivity, checkout, merge, m-search, notify, subscribe, unsubscribe, patch, search, and connect.

 What is app.all() used for ?

This is used for loading middleware functions at a path for all request methods.

Screen Shot 2016-04-03 at 11.42.20 PM

What are different response type in express?

Method Description
res.download() Prompt a file to be downloaded.
res.end() End the response process.
res.json() Send a JSON response.
res.jsonp() Send a JSON response with JSONP support.
res.redirect() Redirect a request.
res.render() Render a view template.
res.send() Send a response of various types.
res.sendFile() Send a file as an octet stream.
res.sendStatus() Set the response status code and send its string representation as the response body.

 What is middleware in express ?

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.

Middleware functions can perform the following tasks:

  • Execute any code.
  • Make changes to the request and the response objects.
  • End the request-response cycle.
  • Call the next middleware function in the stack.

 

An Express application can use the following types of middleware:

Example:

  • body-parser – This is a node.js middleware for handling JSON, Raw, Text and URL encoded form data.
  • cookie-parser – Parse Cookie header and populate req.cookies with an object keyed by the cookie names.

 How to serve static files in express ?

Express provides a built-in middleware express.static to serve static files, such as images, CSS, JavaScript etc.

app.use(express.static('public'));

We will keep few images in public/images sub-directory as follows:

node_modules
server.js
public/
public/images
public/images/logo.png

Node.js

Node.js is an open-source, cross-platform runtime environment for developing server-side Web applications. Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient.

What is event loop in Node.js ?

A JavaScript runtime contains a inbuilt message queue, which is a list of messages to be processed. In a typical node.js environment  each message is associated with a call back function. When the stack is empty, a message is taken out of the queue and processed. The processing consists of calling the associated callback function. The message processing ends when the stack becomes empty again and this process is repeated.

Handling I/O in node.js is  typically performed via events and callbacks, so when the application is waiting for a database  to insert/update  to finish, it can still process other things like user input.

Is Node.js single threaded ? How can you make it multithreaded?

Yes. You can make it multithreading by using a node cluster.

What is clustering in Node.js?

A single instance of Node.js runs in a single thread. To take advantage of multi-core systems the user will sometimes want to launch a cluster of Node.js processes to handle the load.

Example:

Source:

Screen Shot 2016-05-09 at 10.16.07 PM

What is preferred way to handle unhandled exceptions in node.js?

Unhandled exceptions in Node.js can be caught at the Process level by attaching a handler for uncaughtException event.

process.on('uncaughtException', function(err) {
  console.log('Caught exception: ' + err);
});

What is NPM?

npm is packaging ecosystem for node.js, is the largest ecosystem of open source libraries in the world.

What is Grunt/Gulp?

Grunt or Gulp both are popular task runner for node.js application.  It is usually used to group tasks like minification, compilation, unit testing, linting etc to be done in automated fashion.

Bonus questions:

What are promises ?

As Node.js become popular it has become very critical for javascript programmers to write asynchronous code. Native javascript prior to version 1.5 does not provide a good way to write asynchronous code. Programmers were forced to use callback from a callback which usually end up in un maintainable code. This concept is also called as callbackhell. In earlier node.js days Q library was very popular which makes it easier to write asynchronous code. Today, ES6 natively supports Promises.

pinky-promise_2The Promise object is used for asynchronous computations. A Promise represents an operation that hasn’t completed yet, but is expected in the future.It allows you to associate handlers to an asynchronous action’s eventual success value or failure reason.

A Promise is in one of these states:

  • pending: initial state, not fulfilled or rejected.
  • fulfilled: meaning that the operation completed successfully.
  • rejected: meaning that the operation failed.

Example | Demo

function asyncGreet(name) {
 return new Promise(function(resolve, reject) {
 setTimeout(function() {

 if (1 === 1) {
 return resolve('Hello, ' + name + '!');
 } else {
 return reject('Greeting ' + name + ' is not allowed.');
 }
 }, 1000);


 });
}

var promise = asyncGreet('Robin Hood');
promise.then(function(greeting) {
 alert('Success: ' + greeting);
}, function(reason) {
 alert('Failed: ' + reason);
});

ES6 ?

ES6 is the new way for writing javascript. A lot of new features is added with ES6 to make javascript feels like a better programming language. Node version greater than v4 supports ES6 natively. This make it easier to use all new features.  Read more about ES6 here.

Testing JavaScript Application ?

Mocha and Jasmine are two most popular testing framework which are very well integrated with node.js.

✓ Both support Asynchronous Tests
✓ Both support CI (continuos integration) build. Can be easily integrated with Jenkins.
✓ Both allows you to organize tests in suits
✓Supports both client-side and server-side testing

Some key differences :

Jasmine Mocha
Support BDD (Behavior driven development) and TDD (Test driven development) Supports both BDD (Behavior driven development) and TDD (Test driven development)
Supports Browser interface (to run the test) Supports both command line and browser
Spies(Can be used for mocking) No Spies.
Built-in Matchers(ex:Expect(x).toBeUndefined()) Nothing in build.

Sample Mocha Test:

Demo

describe('Simple tests', function(){
 var j = true;
 var i = false;
 it('true = false?', function(){
 i.should.equal(i);
 });
 it('true = true?', function(){
 i.should.equal(j);
 });
 it('i[3] = j?', function(){
 var i = [1,2,3, "Hello"];
 i[2].should.equal(3);
 });
 });

 

Coding exercises:

Rebecca Murphey’s  JS Assessment:

This is the most favorite JS assessment exercise which interviewers usually ask. I would suggest to come up with your own creative solutions to the exercise instead of just going the solution. This is my solutions to the exercise. The goal of this exercise is to pass as many test cases in the limited time.

Algorithm Style Questions:

Usually you will be asked to solve a algorithm style question. Most of the companies if you are applying for contract role usually don’t usually ask for Big O analysis. If you can solve the problem in the given time you will get a job. I have listed all the common question in my github repo that i have seen so far. Other places where you can practice these type of questions for free are hackerrank and leetcode.

JavaScript Fundamental Questions:

Some companies might also ask you to write a code that use inheritance in javascript or write a code that uses a closure. The goal here is test javascript fundamentals. Here is list of questions with solutions that I have seen usually in a interview.

Sitepoint also have good list of questions to practice :https://www.sitepoint.com/5-typical-javascript-interview-exercises/

Node.js/Express.js Coding Questions:

Usually you will be presented with a broken API built on Node.js and Express.js. You will be asked to fix it in a limited time. Here is the solution to above problem.

 

 

 

 

 

 

 

 

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s