2

I am new to javascript language. The format is given on web, I tried but it giving the undefined result.

var name = {
  a : 'a',
  b:'b',c:'c'
};
console.log(name.a);// undefined
console.log(name);// '[object object]'

The output is undefined ? why

Minion
  • 857
  • 11
  • 15

2 Answers2

6

You have a conflict with window.name. If you use name in a global context, the value is stringified. The solution is to use the variable only within a function context instead, or anywhere outside of global scope:

var f = function(){
  var name = {
    a : "a",
    b : "b",
    c : "c"
  };
  console.log(name.a);
  console.log(name);
}

f();
Karl Reid
  • 2,067
  • 1
  • 8
  • 15
  • 3
    OP may need more explanation since they are new to javascript – charlietfl Oct 20 '17 at 17:31
  • yeah, it took me a minute to find some info myself :) best kind of question- I had no idea that this was an issue until I saw the question, so I learned something too. – Karl Reid Oct 20 '17 at 17:36
3

name is a reserved predefined word in javascript

Quote:

you'd better avoid the following identifiers as names of JavaScript variables. These are predefined names of implementation-dependent JavaScript objects, methods, or properties (and, arguably, some should have been reserved words):

Sagiv b.g
  • 28,620
  • 8
  • 59
  • 91