10 JavaScript concepts every Node developer must master

Want to build efficient and scalable Node.js applications? Learn how to make JavaScript work for you, not against you.

bykst (CC0)

Node.js went from an out-of-the-box idea to a mainstay in record time. Today, it's a de facto standard for creating web applications, systems software, and more. Server-side Node frameworks like Express, build-chain tools like Webpack, and a host of utilities for every need make Node a hugely popular way to leverage the power and expressiveness of JavaScript on the back end. 

Although Node now has competition from Deno and Bun, it remains the flagship JavaScript platform on the server.

Node owes much to JavaScript for its enormous popularity. JavaScript is a multiparadigm language that supports many different styles of programming, including functional programming, reactive programming, and object-oriented programming. It allows the developer to be flexible and take advantage of the various programming styles.

But JavaScript can be a double-edged sword. The multiparadigm nature of JavaScript means that nearly everything is mutable. Thus, you can’t brush aside the probability of object and scope mutation when writing Node.js code. Because JavaScript lacks tail-call optimization (which allows recursive functions to reuse stack frames for recursive calls), it’s dangerous to use recursion for large iterations. In addition to pitfalls like these, Node is single-threaded, so it’s imperative for developers to write asynchronous code. Node also suffers from facepalms common to all languages, like swallowing errors.

JavaScript can be a boon if used with care—or a bane if you are reckless. Following structured rules, design patterns, key concepts, and basic rules of thumb will help you choose the optimal approach to a problem. Which key concepts should Node.js programmers understand? Here are the 10 JavaScript concepts that I believe are most essential to writing efficient and scalable Node.js code.

JavaScript closures

A closure in JavaScript is an inner function that has access to its outer function's scope, even after the outer function has returned control. A closure makes the variables of the inner function private. Functional programming has exploded in popularity, making closures an essential part of the Node developer’s kit. Here's a simple example of a closure in JavaScript:


let count = (function () {
     var _counter = 0;
     return function () {return _counter += 1;}
})();

count();
count();
count();

>// the counter is now 3

The variable count is assigned an outer function. The outer function runs only once, which sets the counter to zero and returns an inner function. The _counter variable can be accessed only by the inner function, which makes it behave like a private variable.

The example here is a higher-order function (or metafunction, a function that takes or returns another function). Closures are found in many other applications. A closure happens anytime you define a function inside another function and the inner function gets both its own scope and access to the parent scope—that is, the inner function can “see” the outer variables, but not vice versa. 

This also comes in handy with functional methods like map(innerFunction), where innerFunction can make use of variables defined in the outer scope.

JavaScript prototypes

Every JavaScript function has a prototype property that is used to attach properties and methods. This property is not enumerable. It allows the developer to attach methods or member functions to its objects. JavaScript supports inheritance only through the prototype property. In case of an inherited object, the prototype property points to the object’s parent. A common approach to attach methods to a function is to use prototypes as shown here:


function Rectangle(x, y) {
     this.length = x;
     this.breadth = y;
}

Rectangle.prototype.getDimensions = function () {
     return { length : this._length, breadth : this._breadth };
};

Rectangle.prototype.setDimensions = function (len, bred) {
     this.length = len;
     this.breadth = bred;
};

Although modern JavaScript has pretty sophisticated class support, it still uses the prototype system under the hood. This is the source of much of the language’s flexibility. 

Defining private properties using hash names

In the olden days, the convention of prefixing variables with an underscore was used to indicate that a variable was supposed to be private. However, this was just a suggestion and not a platform-enforced restriction. Modern JavaScript offers hashtag private members and methods for classes:


class ClassWithPrivate {
  #privateField;
  #privateMethod() { }
}

Private hash names is a newer and very welcome feature in JavaScript! Recent Node versions and browsers support it, and Chrome devtools lets you directly access private variables as a convenience. 

Defining private properties using closures

Another approach that you will sometimes see for getting around the lack of private properties in JavaScript’s prototype system is using a closure. Modern JavaScript lets you define private properties by using the hashtag prefix, as shown in the above example. However, this does not work for the JavaScript prototype system. Also, this is a trick you will often find in code and its important to understand what it is doing.

Defining private properties using closures lets you simulate a private variable. The member functions that need access to private properties should be defined on the object itself. Here's the syntax for making private properties using closures:


function Rectangle(_length, _breadth) {
     this.getDimensions = function () {
     return { length : _length, breadth : _breadth };
     };

     this.setDimension = function (len,bred) {
     _length = len;
     _breadth = bred
     };
}

JavaScript modules

Once upon a time, JavaScript had no module system, and developers devised a clever trick (called the module pattern) to rig up something that would work. As JavaScript evolved, it spawned not one but two module systems: the CommonJS include syntax and the ES6 require syntax. 

Node has traditionally used CommonJS, while browsers use ES6. However, recent versions of Node (in the last few years) have also supported ES6. The trend now is to use ES6 modules, and someday we’ll have just one module syntax to use across JavaScript. ES6 looks like so (where we export a default module and then import it):


// Module exported in file1.js…
export default function main() { }
// …module imported in file2.js
import main from "./file1";

You’ll still see CommonJS, and you’ll sometimes need to use it to import a module. Here's how it looks to export and then import a default module using CommonJS:


// module exported in file1.js…
function main = () { }
module.exports = main;
// …module imported in file2.js

Error handling

No matter what language or environment you are in, error handling is essential and unavoidable. Node is no exception. There are three basic ways you’ll deal with errors: try/catch blocks, throwing new errors, and on() handlers.

Blocks with try/catch are the tried-and-true means for capturing errors when things go wrong:


try {
  someRiskyOperation();
catch (error) {
  console.error(“Something’s gone terribly wrong”, error);
}

In this case, we log the error to the console with console.error. You could choose to throw the error, passing it up to the next handler. Note that this breaks code flow execution; that is, the current execution stops and the next error handler up the stack takes over:


try {
  someRiskyOperation();
catch (error) {
   throw new Error(“Someone else deal with this.”, error);
}

Modern JavaScript offers quite a few useful properties on its Error objects, including Error.stack for getting a look at the stack trace. In the above example, we are setting the Error.message property and Error.cause with the constructor arguments.

Another place you’ll find errors is in asynchronous code blocks where you handle normal outcomes with .then(). In this case, you can use an on(‘error’) handler or onerror event, depending on how the promise returns the errors. Sometimes, the API will give you back an error object as a second return value with the normal value. (If you use await on the async call, you can wrap it in a try/catch to handle any errors.)  Here’s a simple example of handling an asynchronous error:


someAsyncOperation()
  .then(result => {
    // All is well
  })
  .catch(error => {
    // Something’s wrong
    console.error("Problems:", error);
  });

No matter what, don’t ever swallow errors!  I won't show that here because someone might copy and paste it. Basically, if you catch an error and then do nothing, your program will silently continue operating without any obvious indication that something went wrong. The logic will be broken and you’ll be left to ponder until you find your catch block with nothing in it. (Note, providing a finally{} block without a catch block will cause your errors to be swallowed.)

JavaScript currying

Currying is a method of making functions more flexible. With a curried function, you can pass all of the arguments that the function is expecting and get the result, or you can pass only a subset of arguments and receive a function back that waits for the remainder of the arguments. Here's a simple example of a curry:


var myFirstCurry = function(word) {
     return function(user) {
            return [word , ", " , user].join("");
     };
};

var HelloUser = myFirstCurry("Hello");
HelloUser("InfoWorld"); // Output: "Hello, InfoWorld"

The original curried function can be called directly by passing each of the parameters in a separate set of parentheses, one after the other:


myFirstCurry("Hey, how are you?")("InfoWorld"); // Output: "Hey, how are you?, InfoWorld"

This is an interesting technique that allows you to create function factories, where the outer functions let you partially configure the inner one. For example, you could also use the above curried function like so:


let greeter = myFirstCurry("Namaste");
greeter("InfoWorld"); // output: “Namaste, InfoWorld”

In real-world usage, this idea can be a help when you need to create many functions that vary according to certain parameters.

JavaScript apply, call, and bind methods

Although it’s not every day that we use them, it’s good to understand what the call, apply, and bind methods are. Here, we are dealing with some serious language flexibility. At heart, these methods allow you to specify what the this keyword resolves to.

In all three functions, the first argument is always the this value, or context, that you want to give to the function.

Of the three, call is the easiest. It's the same as invoking a function while specifying its context. Here’s an example:


var user = {
     name: "Info World",
     whatIsYourName: function() {
     console.log(this.name);
     }
};

user.whatIsYourName(); // Output: "Info World",
var user2 = {
     name: "Hack Er"
};

user.whatIsYourName.call(user2); // Output: "Hack Er"

Note that apply is nearly the same as call. The only difference is that you pass arguments as an array and not separately. Arrays are easier to manipulate in JavaScript, opening a larger number of possibilities for working with functions. Here's an example using apply and call:


var user = {
     greet: "Hello!",
     greetUser: function(userName) {
     console.log(this.greet + " " + userName);
     }
};

var greet1 = {
     greet: "Hola"
};

user.greetUser.call(greet1,"InfoWorld") // Output: "Hola InfoWorld"
user.greetUser.apply(greet1,["InfoWorld"]) // Output: "Hola InfoWorld"

The bind method allows you to pass arguments to a function without invoking it. A new function is returned with arguments bounded preceding any further arguments. Here's an example:


var user = {
     greet: "Hello!",
     greetUser: function(userName) {
     console.log(this.greet + " " + userName);
     }
};

var greetHola = user.greetUser.bind({greet: "Hola"});
var greetBonjour = user.greetUser.bind({greet: "Bonjour"});

greetHola("InfoWorld") // Output: "Hola InfoWorld"
greetBonjour("InfoWorld") // Output: "Bonjour InfoWorld"

JavaScript memoization

Memoization is an optimization technique that speeds up function execution by storing results of expensive operations and returning the cached results when the same set of inputs occur again. JavaScript objects behave like associative arrays, making it easy to implement memoization in JavaScript. Here's how to convert a recursive factorial function into a memoized factorial function:


function memoizeFunction(func) {
     var cache = {};
     return function() {
          var key = arguments[0];
          if(cache[key]) {
          return cache[key];
          }
          else {
          var val = func.apply(this, arguments);
          cache[key] = val;
          return val;
          }
     };
}

var fibonacci = memoizeFunction(function(n) {
     return (n === 0 || n === 1) ? n : fibonacci(n - 1) + fibonacci(n - 2);
});

JavaScript IIFE

An immediately invoked function expression (IIFE) is a function that is executed as soon as it is created. It has no connection with any events or asynchronous execution. You can define an IIFE as shown here:


(function() {
     // all your code here
     // ...
})();

The first pair of parentheses function(){...} converts the code inside the parentheses into an expression.The second pair of parentheses calls the function resulting from the expression. An IIFE can also be described as a self-invoking anonymous function. Its most common usage is to limit the scope of a variable made via var or to encapsulate context to avoid name collisions.

There are also situations where you need to call a function using await, but you're not inside an async function block. This happens sometimes in files that you want to be executable directly and also imported as a module. You can wrap such a function call in an IIFE block like so:


(async function() {
     await callAsyncFunction()
})();

Useful argument features

Although JavaScript doesn’t support method overloading (because it can handle arbitrary argument counts on functions), it does have several powerful facilities for dealing with arguments. For one, you can define a function or method with default values:


function greet(name = 'Guest')
 { 
   console.log(`Hello, ${name}!`); 
 } 
  greet(); // Outputs: Hello, Guest! 
  greet('Alice'); // Outputs: Hello, Alice!

You can also accept and handle all the arguments at once, so that you can handle any number of arguments passed in. This uses the rest operator to collect all the arguments into an array:


function sum(...numbers) { 
  return numbers.reduce((total, num) => total + num, 0); 
} 

console.log(sum(1, 2, 3)); // Outputs: 6 
console.log(sum(4, 5)); // Outputs: 9

If you really need to deal with differing argument configurations, you can always check them:


function findStudent(firstName, lastName) {
    if (typeof firstName === 'string' && typeof lastName === 'string') {
        // Find by first and last name
    } else if (typeof firstName === 'string') {
        // Find by first name
    } else {
        // Find all students
    }
}

findStudent('Alice', 'Johnson');  // Find by first and last name
findStudent('Bob');               // Find by first name
findStudent(); // Find all

Also, remember that JavaScript includes a built-in arguments array. Every function or method automatically gives you the arguments variable, holding all the arguments passed to the call.

Conclusion

As you become familiar with Node, you’ll notice there are many ways to solve almost every problem. The right approach isn't always obvious. Sometimes, there are several valid approaches to a given situation. Knowing about the many options available helps.

The 10 JavaScript concepts discussed here are basics every Node developer will benefit from knowing. But they're the tip of the iceberg. JavaScript is a powerful and complex language. The more you use it, the more you will understand how vast JavaScript really is, and how much you can do with it.