1

I want to check if a variable is defined before using it, so I wrote something like this

if(!variable){
    return null;
}

But it throws an error

ReferenceError: variable is not defined

If I do it like this

if(typeof variable === 'undefined'){
    return null;
}

It works as expected.

What is the difference between the approaches and why it didn't return null in the first example but instead it died with the error ?

2

1 Answer 1

2

When !variable is evaluated it tries to get the value of the variable which as per spec will throw an ReferenceError.

But calling typeof will not initially try to get the value of the variable, instead it will check whether the passed expression is a reference, if so then it will check if it is resolvable if nor undefined is returned.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.