user12913618
user12913618

Reputation:

using a non existing variable as a property of global object throws undefined. why?

//undefined . Why not a reference error instead?
console.log(window.b);

as there is no such global variable as b, console should throw a reference error but it says b is undefined. Which i think is implying variable b is declared globally but not assigned.

Can you explain what is happening here? (sorry if my question is silly) please explain on beginner level.

Upvotes: 1

Views: 157

Answers (3)

Ziad Adeela
Ziad Adeela

Reputation: 496

You can access an object in many ways. For example:

  • foo.bar
  • myObject['prop']

We call each of foo, myObject the base value. While bar, prop the reference name.

A reference error occurs when the reference is unresolvable. And this happens when the base value is undefined.

In your case, window is a global object which is defined. As a result of this, the base value is defined and this will not cause a reference error.

You can refer to this useful link for more clarification on the meaning of undefined in JS.

Upvotes: 0

D. Pardal
D. Pardal

Reputation: 6597

Which i think is implying variable b is declared globally but not assigned.

Not really. If you try to access a property that doesn't exist from an object, you get undefined. Example:

const obj = { a: "a" };

console.log(`Property "b" exists in obj? ${"b" in obj}`);
console.log(`Value of obj.b: ${obj.b}`);

The same thing happens with the global object, however, you can't use b directly:

var a = "a";

console.log(`Property "b" exists in the global oject? ${"b" in window}`);
console.log(`Value of window.b: ${window.b}`);

try {
  console.log(`Value of b: ${b}`);
} catch(err) {
  console.log(`Not possible to get the value of b. Error:\n ${err.name}: ${err.message}`);
}

Upvotes: 1

henok
henok

Reputation: 894

According to the Docs

The ReferenceError object represents an error when a non-existent variable is referenced.

but when you reference window.b where window is defined as an object then accessing b is requesting a non existing object and according to this default value for non existing object properties is undefined

Upvotes: 0

Related Questions