0

I have this code:

console.log(apple);

If I run the program, I get the following result:

console.log(apple);
            ^

ReferenceError: apple is not defined

This is what I expected, but if I modify the code to print the apple variable from the global object, I get undefined

console.log(global.apple);

Result:

undefined

How is this undefined? As per my understanding, this should give the ReferenceError too right? Sorry if this is a simple concept, I am trying to understand the fundamentals. Any reference would be helpful.

sam
  • 43
  • 1
  • 2
  • 7
  • 1
    "*this should give the ReferenceError too right?*" no, *reading a property* does not throw reference errors, only *reading a variable*. – VLAZ Jun 08 '21 at 14:23
  • 1
    `global` is defined (by design). But `global.anything` is undefined. – Jeremy Thille Jun 08 '21 at 14:25

1 Answers1

4

What you're forbidden to do is reference a standalone identifier that the interpreter cannot resolve.

Referencing a property of an object - even if the property doesn't exist - is perfectly fine. It will result in undefined, but it won't throw.

const obj = {};
console.log(obj.foo);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320