Little known features of JavaScript

Viral Shah
10 min readNov 26, 2018

JavaScript is often said to be the easiest language to start with and the hardest to master. I couldn’t agree more. This is because JavaScript is a really old & a really flexible language. It is full of mysterious syntaxes and obsolete features. I’ve been working with JavaScript for years now and to date, every now and then, I still stumble upon some hidden syntax or tricks that I never knew existed.

I’ve tried to list down some of the lesser known features of JavaScript. While some of these features are invalid in the strict mode, they are still perfectly valid JavaScript code. However please note, I do not suggest that you start using all of these features. While they are definitely cool, there is a good chance you might start getting angry looks from your teammates, if you start using them.

All the source code used is available here. Happy Coding!

Note: I am not including things like Hoisting, Closures, Proxies, Prototypal inheritance, async-await, generators, etc. While these features may be less understood, they are still pretty well known.

Void Operator

JavaScript has a unary void operator. You might have seen it used as void(0) or void 0 . It has a single purpose in life — Evaluate the expression to its right and return undefined. Using ‘0’ is just a convention. You don’t necessarily have to use ‘0’, it can be any valid expression like void <expression> and it still returns undefined.

void operator

Why create a special keyword to return undefined instead of just returning undefined?
Sounds a bit redundant, doesn’t it ?

🚩 Fun Fact

Well, turns out, before ES5 you could actually assign a new value to the original undefined likeundefined = "abc" , in most browsers.
Hence, defining the undefined!
In those days, using void was a way to ensure, you are always returning the original undefined.

Constructor Brackets are optional

Yes, the parentheses we add after class name while invoking a constructor — completely optional! 😮 (Provided that you don’t need to pass any arguments to the Constructor)

Both the code styles below are considered to be valid JS syntax, and will give you exact same results!

Constructor brackets are optional

IIFE Brackets can be skipped

The syntax for IIFE (Immediately Invoked Functional Expression) was always a bit odd for me.
What’s up will all the brackets?

Well turns out those extra brackets are needed just to tell the JavaScript parser, that the upcoming code is a Functional Expression and not a Function. Knowing this, one can imagine, there are many ways to skip those extra brackets & still make a valid IIFE.

IIFE (without return)

The void operator tells parser that the code is functional expression. Hence, we can skip brackets around function definition. And guess what? We can use any unary operators (void, +, !, -, etc.) and this still works!

This is so cool!

However, if you are a keen observer, you may wonder,

Won’t the unary operator affect any result returned from the IIFE ?

Well, it will affect the result. But the good news is, if you care about the result and say you are storing it in some variable, then you don’t need the extra brackets in the first place.

That’s true!

IIFE with return

We add those brackets just for better human readability.

For a deeper dive on IIFE checkout this cool article by Chandra Gundamaraju

With Statement

Did you know, JavaScript has a with statement block? with is actually a keyword in JS. The syntax to write a with block is as follows

with (object)
statement
// for multiple statements add a blockwith (object) {
statement
statement
...
}

with adds all the properties of the “object” passed, in the scope chain used for evaluating the statements.

with block example

🚩 Fun Fact

With block sounds pretty cool, right? It’s even better than object destructuring.
Well, not really.
The use of the with statement is generally discouraged, as it was deprecated. It is completely forbidden in strict mode. Turns out, with blocks adds some performance and security problems in the language. Bummer!

The Function constructor

The function statement is not the only way to define a new function; you can define your function dynamically using Function() constructor along with the new operator.

Dynamic function with Function constructor

The last constructor param is the stringified code of the function and other parameters before that are the function arguments.

🚩 Fun Fact

Function constructor is the mother of all constructors in JavaScript. Even Object’s constructor is Function constructor. And Function’s own constructor is also Function itself. Hence, callingobject.constructor.constructor... enough times will eventually return the Function constructor on any object in JavaScript.

Function Properties

We all know Functions are first class objects in JavaScript. Hence, no one is stopping us from adding custom properties to a Function. It is perfectly valid JS thing to do. Yet, it is rarely used.

So when would we want to do this?

Well, there are a few good use cases for this. For example,

Configurable Functions

Let’s say we have a function called greet. We want our function to print a different greeting message based on different locales. This locale should also be configurable. We can maintain a global locale variable somewhere or we can implement the function using functional properties as shown below

greet function with locale property

Function with Static Variables

Another similar example. Let’s say, you want to implement a Number Generator that generates a sequence of ordered numbers. Normally, you’ll use Class or IIFE with a static counter variable to keep track of last value. This way we restrict access to the counter and also avoid polluting the global space with extra variables.

But what if we want the flexibility to read or even modify the counter & yet not pollute the global space?

Well we could still create a Class, with a counter variable and some extra methods to read it; or we can be lazy and just use properties on a function.

generateNumber function with counter property

Phew!! This is a long list & we are just about halfway there. If you wanna take a break, now will be a good time. If not, you are a brave warrior & I salute you.

Let’s continue!

Arguments Properties

I’m sure most of you are aware of arguments object inside a function. It’s an array like object available inside all the functions. It has the list of arguments passed to the function while it was invoked. But it also has some other interesting properties on it,

  • arguments.callee: Refers to the function currently invoked
  • arguments.callee.caller: Refers to the function that has invoked the current function
callee & caller

Note: While the ES5 forbids the use of callee & caller in strict mode, it is still commonly found in many compiled libraries. So, it is worth learning them.

Tagged Template Literals

Unless you’ve been living under a rock, you would have heard about the Template literals. Template literals are one of the many cool additions by ES6. However, do you know about Tagged Template literals?

Template literals

Tagged Template literals allow you to have more control over parsing the template literals to a string, by adding a custom tag to the template literals. Tag is simply a parser function which gets array of all the strings and values interpreted by the string template. The tag function is expected to return the final string.

In following example, our custom tag — highlight, interprets the values for template literal and also wraps the interpreted values in the result string with a <mark> element, for highlighting.

highlight tagged template literal

Many libraries have found interesting use cases to leverage this feature. Following are some cool examples,

styled-components for React
es2015-i18n-tag for translation & internationalization
chalk for colorful logs

Getters & Setters

For the most parts, JavaScript Objects are simple. Let’s say if we have a user object and we try to access age property on it using user.age we get the value of age property if its defined or we get undefined if it’s not. Simple.

But, it doesn’t have to be this simple. JavaScript Objects have the concept of Getters and Setters. Instead of directly returning the value on object we can write our custom Getter function to return whatever we want. Same thing about setting a value.

This allows us to have powerful concepts like virtual fields, field validations, side-effects while getting or setting a field

ES5 Getters & Setters

Getters & Setters are not new addition by ES5; they have always been there. ES5 simply adds a convenient syntax to an existing feature. To learn more about Getters & Setters refer this nice article

Colors, a popular node.js library, is a cool example of leveraging Getters.

The library extends String class and adds a bunch of Getter methods on it. This allows us to convert any string to its colored version for easy logging, by simply accessing properties on it.

Comma operator

JavaScript has a comma operator. It allows us to write multiple expressions separated by comma in a single line and return the result of last expression

// syntax
let result = expression1, expression2,... expressionN

Here, all the expressions will get evaluated and the result variable will be assigned the value returned by expressionN.

You might have already used Comma operator in a for loop

for (var a = 0, b = 10; a <= 10; a++, b--)

Sometimes it helps when writing multiple statements in a single line

function getNextValue() {
return counter++, console.log(counter), counter
}

or writing short lamda functions

const getSquare = x => (console.log (x), x * x)

+ Plus Operator

Ever wanted to quickly convert a string to a number?

Just prefix the string with + operator.
Plus operator also works for negative, octal, hexadecimal, exponential values. What’s more, it even converts a Date or Moment.js object to the timestamp!

Plus operator

!! Bang Bang Operator

Okay, technically its not a separate JavaScript operator. It’s just the JavaScript negation operator used twice.

But Bang Bang sounds so cool! Bang Bang or Double Bang is a neat trick to convert any expression to a Boolean value.

If the expression is a truthy value, it return true; otherwise it returns false.

Bang Bang operator

~ Tilde Operator

Let’s face it — Nobody cares about the Bitwise operators.
When are we ever gonna use it!

Well, there is an everyday use case for the Tilde or Bitwise NOT operator.

Turns out when used with a number, the Tilde operator effective does
~N => -(N+1) . This expression evaluates to “0” only when N == -1

We can leverage this by putting ~ in front of theindexOf(...) function to do a boolean check if an item exists in a String or an Array.

indexOf with Tilde operator

Note: ES6 & ES7 added a new .includes() method in String & Array, respectively. Definitely, it’s a more cleaner way than tilde operator to check if an item exists in an Array or a String.

Labelled statements

JavaScript has the concept of label statements. It allows us to name loops and blocks in JavaScript. We can then use these labels to refer back to the code later while using break or continue .

Labelled statements are particularly handy in nested loops. But we can also use them to simply organize code into blocks or create a breakable block

labelled statements

Note: Unlike some other languages, JavaScript doesn’t have goto construct. Hence, we can only use labels with break and continue.

If you know any more of such JavaScript quirks or have found interesting use-cases to leverage these features, please share your experiences below. I would love to hear about it!

I ❤️ JavaScript & enjoy writing articles about it. But they do take a lot of time & effort. If you have enjoyed this article please share & recommend it.

Happy Coding!

📝 Read this story later in Journal.

🗞 Wake up every Sunday morning to the week’s most noteworthy Tech stories, opinions, and news waiting in your inbox: Get the noteworthy newsletter >

--

--

Viral Shah

Passionate programmer, Wishful writer, Rookie gamer, Potential philosopher