Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Top 4 JavaScript Concepts a Node.js Beginner Must Know

DZone's Guide to

Top 4 JavaScript Concepts a Node.js Beginner Must Know

1. Non-blocking or Asynchronous I/O, 2. Prototype, 3. Modules, 4. Callbacks

· Web Dev Zone
Free Resource

Should you build your own web experimentation solution? Download this whitepaper by Optimizely to find out.

Wouldn’t it be awesome if you only had to know one programming language for building a full stack application? Ryan Dahl put this thought into action when he created Node.js.

Node.js is server side framework that is built upon Chrome’s powerful V8 JavaScript engine. Though, originally written in C++, you write all Node.js applications in JavaScript, and it allows you to use this client-side language on the server side.

See, problem solved. One language to rule them all. But this also brings you to the fact that now your whole application is using the same language. That means you have can focus on honing your knowledge of that one language. That’s the topic of this article. 

Here are the 4 bare minimum concepts that you should be practicing to become great at developing in Node.js. I’ll try to keep the article short.

1. Non-blocking or Asynchronous I/O

Since Node.js is a server-side framework, one of its main functions is to handle browser requests. In traditional I/O systems, a request can only be issued when the response (the HTML page) of the previous request has arrived. That’s why, it is called blocking I/O. The server blocks other requests in order to process the current request which causes the browser to wait (in a rotating circle).

Node.js doesn’t follow this principle of I/O. If a request is intended to take a longer time, Node sends that request into an event loop and goes on to handle the next request in the call stack. As soon as the pending request is done processing, it tells node and the response is rendered on the browser.

Lets understand this with a dummy example:

Blocking I/O

// take order for table 1 and wait...
var order1 = orderBlocking(['Coke', 'Iced Tea']);

// once order is ready, take order back to table.
serveOrder(order1);
// once order is delivered, move on to another table.

// take order for table 2 and wait...
var order2 = orderBlocking(['Coke', 'Water']);

// once order is ready, take order back to table.
serveOrder(order2);
// once order is delivered, move on to another table.

// take order for table 3 and wait...
var order3 = orderBlocking(['Iced Tea', 'Water']);

// once order is ready, take order back to table.
serveOrder(order3);
// once order is delivered, move on to another table.

In this example of a restaurant, the waiter takes an order, then waits for the order to complete and then goes back to the table to serve the order each time. When the order is processing, the waiter just waits or blocks orders from other customers.

Non Blocking I/O

// take order for table 1 and move on...
orderNonBlocking(['Coke', 'Iced Tea'], function(drinks){
  return serveOrder(drinks);
});

// take order for table 2 and move on...
orderNonBlocking(['Beer', 'Whiskey'], function(drinks){
  return serveOrder(drinks);
});

// take order for table 3 and move on...
orderNonBlocking(['Hamburger', 'Pizza'], function(food){
  return serveOrder(food);
});

In this example, the waiter takes an order and informs the cook of the order.  Then the waiter goes back to take another order. After the first order is done processing, the waiter takes that order to the respective table and goes on again to take order from other customers. The waiter doesn’t block orders from other customers.

2. Prototype

Prototype is a complex concept in JavaScript. Since you are going to use prototypes a lot in Node.js, every JS developer must know about this concept.

In a language that implements classical inheritance like Java and C++ for the purpose of code reuse, you first make a class (a blueprint for your objects) and then you create objects from that class or extend that class.

However, there is no concept of classes in JavaScript. You first create an object in JavaScript, and then augment your own object or create new objects from it. This is called prototypal inheritence, which is implemented through the prototype.

Every JavaScript object is linked to a prototype object from which it can inherit properties. Prototypes are analogous to classes in other OO lanuages but differ in the fact that they are objects themselves. Every object is linked to Object.prototype, which comes predefined with JavaScript.

If you look up a property via obj.propName or obj['propName']  and the object does not have a property that can be checked via obj.hasOwnProperty('propName') , the JavaScript’s runtime looks up the property in its prototype object. If the prototype object also doesn’t have the given property, its own prototype is checked in turn until a match is found or until it has reached Object.prototype. If that property doesn’t exist in the prototype chain, then it results in a undefined value.

Lets understand this with the following example code:

if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        var F = function () {};
        F.prototype = o;
        return new F();
    };

var otherPerson = Object.create(person);

When you make a new object, you can select an object that should be its prototype. Here, we are adding a create method to the Object  function. The create method creates a new object that uses another object as its prototype, which was passed to it as an argument.

When we make changes to the new object, its prototype remains unaffected. But when we make changes to the prototype object, the changes become visible in all the objects that are based on that prototype.

3. Modules

If you’ve ever worked with packages in Java, modules in Node.js are no different. If not, don’t worry. Modules are simple JavaScript files that contain code for a specific purpose. The module pattern is used to make your code easy to navigate and work with. To use the properties of a module, you have to require it in a JavaScript file the same way you would import a package in a Java class.

There are two types of modules in Node.js.

Core Modules – These are the ones which come pre-compiled with Node.js. The purpose of the core modules is to provide developers with frequently used utilities that eliminate some tedium. Some common core modules are HTTP, URL, EVENTS, FILE SYSTEM, etc.

User Defined Modules – User defined modules are the utilities that a developer makes for a specific purpose in their application. These are required when the core modules are not capable of fulfilling the desired functionality.

Modules are extracted via the require function. If it's a core module, the argument is simply the name of that module. If it’s a user defined module, then the argument is the path of that module in the file system.

e.g.,

// extract a core module like this

var http = require('http);

// extract a user defined module like this

var something = require('./folder1/folder2/folder3/something.js');

4. Callbacks

In JavaScirpt, functions are regarded as first-class objects. That means you can do all the operations with functions that you can do with a regular objects. You can assign functions to a variable, pass these as arguments to methods, declare them as a property of an object, and even return them from functions.

Callbacks are anonymous functions in JS that can be passed as arguments to other functions and can be executed or can be returned from that function to be executed later. This is the basis of callbacks. They are most widely used in functional programming paradigms.

When we pass a callback function as an argument to another function, we only pass the function definition i.e., we never know when that callback function will execute. That totally depends on the mechanism of the calling function. It is “called back” at some later point in time, hence the name. This is the sole basis of the non-blocking or asynchronous behavior of Node.js, as illustrated by the following example.

setTimeout(function() {
    console.log("world");
}, 2000)

console.log("hello");

This is one of the simplest examples of a callback. We passed an anonymous function as an argument, which simply logs some output on the console to the setTimeout  function. Since, it’s only the function definition, it doesn’t know when to execute. That is determined by the calling the setTimeout function via the second argument, which happens after 2 seconds.

First, the second log statement logs the output to the console and then after two seconds, the log statement in the callback function logs the output.

// output

hello
world

That’s it. Those are my top four JavaScript concepts that must be understood as a Node.js beginner. What is in your list? Please tell me in the comments.

Implementing an Experimentation Solution: Choosing whether to build or buy?

Topics:
javascript ,nodejs

Published at DZone with permission of Ankit Singh, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}