www.webdeveloper.com
Results 1 to 2 of 2

Thread: property accessors

  1. #1
    Join Date
    Jul 2014
    Posts
    1

    property accessors

    var foo = {}, bar = {}, object = {};
    object[foo] = 'value';
    console.log(object[bar]);

    Output: value

    How does this work?
    I have declared object[foo] as 'value' but it how does javascript assess object[bar] as 'value' too?
    From developers.mozilla:
    (This also outputs "value", since both foo and bar are converted to the same string)

    Could someone please explain me this concept of bracket notation?

    Thanks

  2. #2
    Join Date
    Oct 2012
    Location
    Croatia
    Posts
    255
    In JavaScript there are two syntaxes for property access:

    object.identifier
    object[expression]

    Using the first style an identifier has to be a literal value. That means that a value has to be embedded directly in code. The overall expression evaluates to the value of an identifier expression. For example:

    Code:
    var o = {x: 1};
    var x = o.x //evaluates to 1
    Using the [ ] property access expression, expression inside the square brackets has to be a string or an expression that can be converted to a type of string. So, here's what JavaScript does with your example:

    Code:
    var foo = {}, bar = {}, object  = {};
    
    //this
    foo[bar] = 'value';
    
    //is the same as this (actually JavaScript does the conversion automatically for you)
    foo['bar'] = 'value'
    Also note that when using the . expression you have to know the name of a property you are accessing (it has to be static, literal value). But if you want to access property that is the result of some computation or it has spaces or something similar in its name you have to use [ ] expression. Consider the following example:

    Code:
          var o = {person: "John", 10: "ten"};
          
          /* 
           * Each property value will be evaluated to undefined because
           * you are using the . property access expression so JavaScript
           * expects the property named i (literally)
           */
          for (var i in o) console.log(o.i);
          
          //property names are evaluated as expected
          for (var i in o) console.log(o[i]);
          
          //syntax error
          console.log(o.5 + 5)
          
          //outputs ten
          console.log(o[5+5]);

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles