1
var obj = {a : 2};
console.log(obj.b); //prints undefined
console.log(b);      //ReferenceError

Here both obj.b and b are not defined. Can anyone explain the reason behind the different outputs?

Priyanjit
  • 305
  • 3
  • 9
  • obj.b is a property of obj, which doesn't exist (hence undefined), b is a variable that doesn't exist (hence reference error) – Lixus Jul 08 '17 at 16:44
  • Possible duplicate of [How does variable assignment work in JavaScript?](https://stackoverflow.com/questions/509579/how-does-variable-assignment-work-in-javascript) – Ian Jul 08 '17 at 16:45
  • You should take a look around, plenty of answers such as [this one](https://stackoverflow.com/questions/509579/how-does-variable-assignment-work-in-javascript) – Ian Jul 08 '17 at 16:45
  • @Ian I checked that answer before posting this question. That answer never really explained the different outputs. – Priyanjit Jul 08 '17 at 16:59

3 Answers3

1

The first is a missing property, the second is a missing variable.

See also the difference here:

console.log(window.b);
console.log(b);  
trincot
  • 317,000
  • 35
  • 244
  • 286
0

obj.b is undefined cause he don't exist in your object and var b does not exist too.

Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
Kirino
  • 3
  • 4
0

You can make the first part work by this

var obj = {a : 2};
console.log(obj.a); //Your property `b` was not defined or you typed `b` instead of `a`

..and the second part by this

var b = 3;
console.log(b);// `b` was not defined at all

Explanations in the comments

James Poulose
  • 3,569
  • 2
  • 34
  • 39