vitaly-t vitaly-t - 1 month ago 5
Javascript Question

Why can't I set a property to undefined?

I'm trying to implement a test where my code works correctly in different Node.js environments, by changing and testing the value of variable

NODE_ENV
.

What I'm stuck with, is trying to understand why the following code:

process.env.NODE_ENV = undefined;

var test = process.env.NODE_ENV || 'empty';

console.log(test);


outputs
undefined
instead of
empty
.

Is that some JavaScript or Node.js feature that I'm missing here?

Tested under Node.js versions: 0.10.47, 4.6.1 and 6.9.1

Answer

It's very subtle: According to the documentation:

Assigning a property on process.env will implicitly convert the value to a string.

So you're getting back "undefined" from process.env.NODE_ENV, not undefined. "undefined" is truthy, so "undefined" || "empty" is "undefined".

You can see that if you modify your script a bit:

'use strict';

process.env.NODE_ENV = undefined;

console.log("process.env.NODE_ENV", typeof process.env.NODE_ENV, process.env.NODE_ENV);
var test = process.env.NODE_ENV || 'empty';

console.log("test", typeof test, test);
console.log("process.env.NODE_ENV", typeof process.env.NODE_ENV, process.env.NODE_ENV);

...which outputs:

process.env.NODE_ENV string undefined
test string undefined
process.env.NODE_ENV string undefined
Comments