DEV Community

Cover image for 10 JavaScript concepts every Node developer must master
USMAN AWAN
USMAN AWAN

Posted on

10 JavaScript concepts every Node developer must master

Node.js has quickly become a standard for building web apps and systems software, thanks to its ability to leverage JavaScript on the back end. Popular frameworks like Express and tools like Webpack contribute to its widespread use. Although competitors like Deno and Bun exist, Node remains the leading server-side JavaScript platform.

JavaScript's multiparadigm nature allows for various programming styles, but it also poses risks like scope and object mutation. The lack of tail-call optimization makes large recursive iterations dangerous, and Node’s single-threaded architecture requires asynchronous code for efficiency. Despite its challenges, following key concepts and best practices in JavaScript can help Node.js developers write scalable and efficient code.

1. 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:

Image description

  • 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.

2. 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:

Image description

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.

3. 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:

Image description

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.

4. 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:

Image description

5. 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):

Image description

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:

Image description

6. 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:

Image description

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:

Image description

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:

Image description

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.)

7. 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:

Image description

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

Image description

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:

Image description

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

8. 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:

Image description

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:

Image description

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:

Image description

9. 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:

Image description

10. 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:

Image description

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:

Image description

11. 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:

Image description

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:

Image description

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

Image description

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.

Top comments (0)