Kyle Fontenot

Photo of Kyle Fontenot

All blog articles

Another small Javascript tidbit for enforcing a number

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