Is the plus sign in + handle a typo in the Node.js documentation for domains?

In this documentation ...

http://nodejs.org/api/domain.html

... this line occurs:

var PORT = +process.env.PORT || 1337;

Is the plus sign a typo? If not, what does this mean?

+4
source share
1 answer

The plus sign is a unary operator, and it loops process.env.PORTover the number from the string.

Background:

// since all env variables are strings
process.env.PORT = 'somePortSavedAsSTring';

process.env.PORTshould be a string, and if nothing is done, node will throw an error. Using a character +prevents this, essentially by adding a line (which changes it from line to number) to zero.

port = ( nothing ) + 'somePortSavedAsSTring'; // makes it a number!

// whitespace is removed by convention, so other programmers know the intent
port = +'somePortSavedAsSTring';

Using the plus sign is simply an eloquent way to provide a variable type. You can use:

var PORT = Number(process.env.PORT) || 1337;

. .

+6

Source: https://habr.com/ru/post/1569792/


All Articles