Shire
Shire

Reputation: 37

Understanding objects

So as I'm learning Javascript I do intend to ask a ton of questions

normally I understand how variable assignments work but this code is a bit confusing why obj[b] = "hello world"?

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

var b = "a" ;

obj[b]; // "hello world" < why is this Hello world?
obj["b"]; // 42

Upvotes: -1

Views: 103

Answers (3)

Vincent J
Vincent J

Reputation: 801

The [] notation allow to access properties/methods in an object dynamically.

Let say you have this dictionnary :

var dict = {
  foo : "bar",
  hello : "world"
};

function access(obj, property){
  return obj[property];
};

console.log(access(dict, "hello"));//world

You cannot do that with dot notation.

Upvotes: 2

Samuel Imolorhe
Samuel Imolorhe

Reputation: 724

obj[b] is equivalent to obj['a'] since you assigned the variable b the value of 'a'

In JavaScript, you can access object properties like an array using bracket notation (mentioned by Andrew) as above or using the dot notation obj.a.

Upvotes: 2

isherwood
isherwood

Reputation: 61124

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

var b = "a" ; // this creates a new variable with string value "a"

obj[b]; // this references the object property having the string value of 
        // variable b, which is "a"

Upvotes: 2

Related Questions