Daniel Kaplan
Daniel Kaplan

Reputation: 67440

Why can't I check if an environment variable is undefined?

This test is printing out fine!!!!. Why isn't it printing out UNDEFINED!!!!?

describe('process test', () => {
    require('dotenv').config()

    it('will make a call from the athena library to get data', async () => {
        process.env["FOO"] = undefined

        const foo: string | undefined = process.env["FOO"]

        if (foo === undefined) {
            console.log('UNDEFINED!!!!')
        } else {
            console.log('fine!!!!')
        }
    })
})

Upvotes: 1

Views: 415

Answers (1)

artem
artem

Reputation: 51689

The documenation says

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

process.env.test = null;
console.log(process.env.test);
// => 'null'
process.env.test = undefined;
console.log(process.env.test);
// => 'undefined'

Which is kind of expected because in reality the environment can store only strings. Assigning undefined will not delete the environment variable, again the documentation says

Use delete to delete a property from process.env.

process.env.TEST = 1;
delete process.env.TEST;
console.log(process.env.TEST);
// => undefined

Upvotes: 7

Related Questions