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
  • 631
  • 1
  • 11
  • 32

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
  • 572,313
  • 128
  • 898
  • 1,281