0

Why does the following code result in three times true?

I was excepting false for the second step.

    function foo() {
        this.bar = function () { };
    };

    console.log("foo - defined : " + typeof window.foo !== 'undefined');
    console.log("bar - defined : " + typeof window.bar !== 'undefined');

    foo();

    console.log("bar - defined : " + typeof window.bar !== 'undefined');
HansMusterWhatElse
  • 671
  • 1
  • 13
  • 34

1 Answers1

3

The + operator's precedence is higher than that of !==. Your expression means

("bar - defined : " + typeof window.bar) !== 'undefined' // always true (or an exception)

instead of

"bar - defined : " + (typeof window.bar !== 'undefined')

If you do the latter explicitly, you'll get the expected output:

foo - defined : true
bar - defined : false
bar - defined : true
Bergi
  • 630,263
  • 148
  • 957
  • 1,375