-3

i am a newbie to JavaScript.I am doing this

var obj = {
    a: "hello world",
    b: 42
};
var b = "a";

console.log(obj[b]);
console.log(obj["b"]);

The results are

    hello world  
42

But how come the console.log(obj[b]);shows hello world? I am confused. please tell me. thanks,.

Cloudboy22
  • 1,496
  • 5
  • 21
  • 39

1 Answers1

0

You can access a value in the object by making use of it's key. In your object obj, it has 2 keys a and b, so to access hello world, you will use obj["a"]. In your case b="a", so "a" can be replaced by variable b, therefore obj[b] will print "hello world"

Nikhil Batra
  • 3,118
  • 14
  • 19
  • so what if i have to put a string a inside variable b?? – Cloudboy22 Jul 20 '15 at 11:14
  • You have just put a string inside variable b, b="a" where "a" is a string, but you have used that string with the "obj[b]", so it will take it as its own key value "a". If you will do console.log(b) then you will get "a", a normal string. – Nikhil Batra Jul 20 '15 at 11:16