DEV Community

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

Posted on

1

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

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay