DEV Community

Cover image for Another small Javascript Tidbit for enforcing a number
KyleFontenot
KyleFontenot

Posted on

Another small Javascript Tidbit for enforcing a number

As I'm getting grasps with Typescript, I watched a really great Youtube tutorial video by Academind (Maximilian) that ran through tons of details on Typescript. In the video, he shows the difference between Typescript and the transpiled Javascript generated which shows a pretty great syntax tool.

...
const something = "5";
    > return +something
    > ...

The + character right before a variable is a way to enforce a number type! In Javascript, literal strings have become completely second-nature to most developers, and one use of it is to enforce a string by using interpolation. This + method is a really nice concise way of filtering a variable for numbers.

The + character before numbers assigns a positive values (and - for negative), so for a dynamic language like Javascript, it's assuming and enforcing the variable as a number under the hood.

This is the first time that I've seen an instance of this syntax used. Good stuff

Discussion (1)

Collapse
lexlohr profile image
Alex Lohr

There's also !!x to enforce boolean and x + '' to enforce a string; however, you might be unsatisfied with the results. Your example might yield NaN and both boolean and string coercion are full of traps for novices and advanced developers alike.

So it might be a better idea to throw an error if the required input format is not met or to use TypeScript to ensure type soundness during development.