Understand how Node.js works

Understand how Node.js works

  • 2016-09-06
  • 1353

To understand how Node.js works, first you need to understand a few key features of JavaScript that make it well suited for server-side development. JavaScript is a simple language, but it is also extremely flexible. This flexibility is the reason why it has stood the test of time. First-class functions and closures make it an ideal language for web applications.

JavaScript has a bad reputation for being unreliable. However, this notion couldn’t be further from the truth. Actually, JavaScript’s bad reputation comes from the DOM’s unreliability. The DOM (docment object model) is the API (application programming interface) that browser vendors provide to interact with the browser using JavaScript. The DOM has idiosyncrasies between browser vendors. However, JavaScript the language is well-defined and can be used reliably across browsers and Node.js. In this tutorial, we discuss a few fundamentals of JavaScript followed by how Node.js used JavaScript to provide a highly performant platform for web applications. Other people complain about how JavaScript handles programming errors (it tries to make invalid code work). However, in such cases, the developers are really to blame, as they need to be careful when working with a highly dynamic language.

Step 1 – Variables

Variables are defined in JavaScript using the var keyword. For example, the following code segment creates a variable foo and logs it to the console. As you saw in the previous article, you would run this code from your console (terminal on Mac OS X and cmd on Windows) usingnode variable.js


var foo = 123;
console.log(foo); // 123

The JavaScript runtime (the browser or Node.js) has the opportunity to define a few global variablesthat we can use in our code. One of them is the console object, which we have been using up to this point. The console object contains a member function (log), which takes any number of arguments and prints them to the console. We will discuss more global objects as they are used. As you will see, JavaScript contains most things you expect a good programming language to have.

Step 2 – Numbers

All numbers in JavaScript have the same floating point number type. Arithmetic operations (+,-,*,/,%) work on numbers as you would expect, as shown in


var foo = 3;
var bar = 5;
console.log(foo + 1);   // 4
console.log(foo / bar); // 0.6
console.log(foo * bar); // 15
console.log(foo - bar); // -2;
console.log(foo % 2);   // remainder: 1

Step 3 – Boolean

Two literals are defined for boolean values: true and false. You can assign these to variables and apply boolean operations to them as you would expect.


var foo = true;
console.log(foo); // true

// Boolean operations (&&, ||, !) work as expected:
console.log(true && true);   // true
console.log(true && false);  // false
console.log(true || false);  // true
console.log(false || false); // false
console.log(!true);          // false
console.log(!false);         // true

Step 4 – Arrays

You can create arrays quite easily in JavaScript using[] Arrays have many useful functions, a few of which are shown


var foo = [];

foo.push(1);         // add at the end
console.log(foo);    // prints [1]

foo.unshift(2);      // add to the top
console.log(foo);    // prints [2,1]

// Arrays are zero index based:
console.log(foo[0]); // prints 2

Object Literals

By explaining these few fundamental types, we have introduced you to object literals. The most common way of creating an object in JavaScript is using the object notation,{}. Objects can be extended arbitrarily at runtime. An example is shown in


var foo = {};
console.log(foo); // {}
foo.bar = 123;    // extend foo
console.log(foo); // { bar: 123 }

Instead of extending it at runtime, you can define which properties go on an object upfront by using the object literal notation shown


var foo = {
    bar: 123
console.log(foo); // { bar: 123 }

You can additionally nest object literals inside object literals, as shown in

var foo = {
    bar: 123,
    bas: {
        bas1: 'some string',
        bas2: 345

And, of course, you can have arrays inside object literals as well, as shown in


var foo = {
    bar: 123,
    bas: [1, 2, 3]

And, you can also have these arrays themselves contain object literals,


var foo = {
    bar: 123,
    bas: [{
        qux: 1
        qux: 2
        qux: 3
console.log(foo.bar);        // 123
console.log(foo.bas[0].qux); // 1
console.log(foo.bas[2].qux); // 2

Object literals are extremely handy as function arguments and return values.

Step 5 – Functions

Functions are really powerful in JavaScript. Most of the power of JavaScript comes from the way it handles the function type. We will examine functions in JavaScript in progressively more involved examples that follow.

Functions 101

A normal function structure in JavaScript is defined in


function functionName() {
    // function body
    // optional return;

All functions return a value in JavaScript. In the absence of an explicit return statement, a function returns undefined. When you execute the code in , you get undefined on the console.


function foo() { return 123; }
console.log(foo()); // 123

function bar() { }
console.log(bar()); // undefined

We will discuss undefined functions more in this article when we look at default values.

Immediately Executing Function

You can execute a function immediatelyafter you define it. Simply wrap the function in parentheses () and invoke it, as shown in


(function foo() {
    console.log('foo was executed!');

The reason for having an immediately executing function is to create a new variable scope. An if else, or while does not create a new variable scope in JavaScript. This fact is demonstrated in


var foo = 123;
if (true) {
    var foo = 456;
console.log(foo); // 456;

The only recommended way of creating a new variable scope in JavaScript is using a function. So, in order to create a new variable scope, we can use an immediately executing function, as shown i

. ief3.js

var foo = 123;
if (true) {
    (function () { // create a new scope
        var foo = 456;
console.log(foo); // 123;

Notice that we choose to avoid needlessly naming the function. This is called an anonymous function, which we will explain next.

Anonymous Function

A function without a name is called an anonymous function. In JavaScript, you can assign a function to a variable. If you are going to use a function as a variable, you don’t need to name the function. demonstrates two ways of defining a function inline. Both of these methods are equivalent.


var foo1 = function namedFunction() { // no use of name, just wasted characters
foo1(); // foo1

var foo2 = function () {              // no function name given i.e. anonymous function
foo2(); // foo2

A programming language is said to have first-class functions if a function can be treated the same way as any other variable in the language. JavaScript has first-class functions.

Higher-Order Functions

Since JavaScript allows us to assign functions to variables, we can pass functions to other functions. Functions that take functions as arguments are called higher-order functions. A very common example of a higher-order function is setTimeout. This is shown in


setTimeout(function () {
    console.log('2000 milliseconds have passed since this demo started');
}, 2000);

If you run this application in Node.js, you will see the console.log message after two seconds and then the application will exit. Note that we provided an anonymous function as the first argument to setTimeout. This makes setTimeout a higher-order function.

It is worth mentioning that there is nothing stopping us from creating a function and passing that in. An example is shown in


function foo() {
    console.log('2000 milliseconds have passed since this demo started');
setTimeout(foo, 2000);

Now that we have a firm understanding of object literals and functions, we can examine the concept of closures.


Whenever we have a function defined inside another function, the inner function has access to the variables declared in the outer function. Closures are best explained with examples.

you can see that the inner function has access to a variable (variableInOuterFunction) from the outer scope. The variables in the outer function have been closed by (or bound in) the inner function. Hence the term closure. The concept in itself is simple enough and fairly intuitive.

function outerFunction(arg) {
    var variableInOuterFunction = arg;

    function bar() {
        console.log(variableInOuterFunction); // Access a variable from the outer scope

    // Call the local function to demonstrate that it has access to arg

outerFunction('hello closure!');              // logs hello closure!

Now the awesome part: The inner function can access the variables from the outer scope even after the outer function has returned. This is because the variables are still bound in the inner function and not dependent on the outer function. shows an example.


function outerFunction(arg) {
    var variableInOuterFunction = arg;
    return function () {

var innerFunction = outerFunction('hello closure!');

// Note the outerFunction has returned
innerFunction(); // logs hello closure!

Now that we have an understanding of first-class functions and closures, we can look at what makes JavaScript a great language for server-side programming.

Source via: dunebook.com


Node.js Tutorial with Visual Studio Code over 4 Hours

Learn How To Deploy Node.Js App on Google Compute Engine

Angular 2 and NodeJS - The Practical Guide to MEAN Stack 2.0

The Complete Node JS Developer Course

The Complete Web Developer Course 2.0