14 Feature and Syntax in Javascript You Might Not Have Heard Of

14 Feature and Syntax in Javascript You Might Not Have Heard Of

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. Read more "14 Feature and Syntax in Javascript You Might Not Have Heard Of"

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.

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

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

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

4. 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 element, for highlighting.

highlight tagged template literal

5. ~ 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.

6. 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 and it still returns undefined.

void operator

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

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

9. With Statement

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

with (object)
// for multiple statements add a block
with (object) {

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

with block example

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

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

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

13. + 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

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

You may also like: 10 More Useful Angular Features You Might Not Have Heard Of

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!

All the source code used is available here.

Happy Coding!!!!!!!!!

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Introduction ES6 features improve your JavaScript code

JavaScript ES6 brings new syntax and new awesome features to make your code more modern and more readable. It allows you to write less code and do more. ES6 introduces us to many great features . In this article, we will explore five of these ES6 features and consider how we can utilize them in improving our JavaScript code. Here are the features of interest:

20 Things to Learn and Effective tips to becoming JavaScript Master

Do you want to get into web development? Or perhaps you’re fascinated with code and software? If so then JavaScript is a good choice for you. In this post, we will for you 20 things to learn and Simple Effective tips on the way to becoming a JavaScript Master