26

If I have a declaration as follows:

var j;

does j==null until I set it equal to something?

1
  • 12
    j==null will be true, but not because j is null. Instead it's because j is undefined, but the == operator does type coercion. The == considers null and undefined to be equal. The === operator is strict, and doesn't do any coercion. Commented May 12, 2012 at 1:38

1 Answer 1

43

No, it has the default value of undefined
But if want to use the !j condition, it will work with both the values (i.e. undefined or null)

Note that (j==null) is true, but (j===null) is false... JavaScript have "falsy" values and sometimes unexpected rules to convert values, plus fancy === operator to compare value and type at the same time.

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

9 Comments

Actually, j == null will evaluate to true, j === null will be false. (But yes, the default value is undefined as j === undefined will be true).
so will writing k === null evaluate to true, since variable k doesn't exist? also i assume i can use the opposite, and say "if(j)", and that will evaluate to false, correct?
@thisissami no, it'll throw a ReferenceError. The tricky thing to get is that undefined is actually a valid value. There are both null and undefined, they are similar but different.
comment was deleted, but I'm leaving the ECMA reference on equality comparison.
They can be manually set or set by values returned from functions, like document.getElementById(elementThatDontExists);
|

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.