Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set an environment variable to undefined in Node.js?

Tags:

node.js

From the REPL, I have the following code:

> process.env.MY_VAR=undefined
undefined
> process.env.MY_VAR
'undefined'

How do I set an envirornment variable to be undefined (ie no value), instead of the string 'undefined'?

like image 664
Mary Avatar asked Sep 15 '25 00:09

Mary


2 Answers

In JavaScript, undefined means that the thing can be accessed, but has an undefined value. You could try and use delete, like:

x = {a:1, b:2, c:3};
delete x.b;
// x is now {a:1, c:3}

But I am not sure you can do that with env properties, and even if you can, be aware that this change will be applied only to YOUR scope. I mean, other scripts relying on that same environment variable will still have it. That's because when you run a script in node, it creates its own environment to execute, copying the current env into its own scope.

like image 151
Felipe N Moura Avatar answered Sep 16 '25 14:09

Felipe N Moura


If you haven't assigned the variable to anything, it should return undefined. If you assign it undefined, implicit type coercion steps in and changes it to a string.

If you're trying to unset an existing variable, you could use delete process.env.MY_VAR and then it will return undefined.

like image 34
LMulvey Avatar answered Sep 16 '25 14:09

LMulvey