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

4
  • I checked the output on chrome, firefox and JsBin also.. Commented Oct 20, 2017 at 17:27
  • Impossible..... Show that jsbin please. Commented Oct 20, 2017 at 17:27
  • jsbin.com/xereluw/edit?js,console,output Commented Oct 20, 2017 at 17:29
  • Good find @Andreas! Commented Oct 20, 2017 at 17:34

2 Answers 2

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();

Sign up to request clarification or add additional context in comments.

2 Comments

OP may need more explanation since they are new to javascript
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.
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):

2 Comments

It's not a reserved word. It's just a preexisting global variable in browsers.
@FelixKling updated

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.