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

Multi tool use


How do I set an environment variable to undefined in 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'?
2 Answers
2
In JavaScript, undefined
means that the thing can be accessed, but has an undefined value.
You could try and use delete
, like:
undefined
delete
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.
env
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.
undefined
undefined
If you're trying to unset an existing variable, you could use delete process.env.MY_VAR
and then it will return undefined
.
delete process.env.MY_VAR
undefined
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.