Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is plus sign in +process a typo in Node.js documentation on domains?

Tags:

node.js

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 it indicate?

like image 676
user1147171 Avatar asked Jan 03 '15 04:01

user1147171


1 Answers

The plus sign is a unary operator, and it coerces process.env.PORT to an number from a string.

Background:

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

process.env.PORT must be a string and if nothing is done node will throw an error. Using the + sign prevents this from happening by essentially adding the string, ( which changes it from a string to a number ) to nothing.

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 this way is just an eloquent way to ensure the variable's type. You could use:

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

and get the exact same effect. It all just depends on your coding style at the end of the day.

like image 142
agconti Avatar answered Oct 19 '22 20:10

agconti