0

Actually i have searched a lot for this on google. This is very basic question.

This is my script

var test = new Object();
test["test"] = 1;

$("#dot").html(test.test);
$("#bracket").html(test["test"]);

This is my html

<div id="dot"></div>
<div id="bracket"></div>

For reference, here is http://jsfiddle.net/PWA5G/1/ URL.

My question is what is exact difference between test.test and test["test"] as my output is same.

This question or thread might have repeated but i didn't find any related results.

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
KuKu
  • 646
  • 2
  • 15
  • 38
  • 4
    See here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Member_Operators – elclanrs Apr 15 '14 at 03:54

3 Answers3

2

The [] operator allows you to use attribute names which cannot be used with . operator. For example

var test = {};
test["invalid-attr"] = 1;
console.log(test["invalid-attr"]);
# 1
console.log(test.invalid-attr);
# ReferenceError: attr is not defined

When we use [] operator with a string in it, it just gets the value corresponding to that by hashing the attribute name we pass. But, if the attribute name is not syntactically valid, then the . operator will fail.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
0

there is some difference, it allows you to use reserved names...but mainly abc['test'] helps when property name is variable.

Like this:

var a ={};
a.q=2;
a.w=3;
a.e=4;

//on user input

var input = event.key
console.log(a[input]);
Muhammad Umer
  • 17,263
  • 19
  • 97
  • 168
0

Just to elaborate in box86rowh with an example. Also note that the target can be either a method or a property. Granted it's a bit contrived, but it demonstrates the flexibility of bracket notation.

<p><input type="checkbox" id="needsBillingAddress"><label for="needsBillingAddress">Different Billing Address</label></p>

<div id="billingAddress">
   <p>Billing Address goes here</p>
</div>

<script>
    $(function() {
        (showHideBillingAddress = function() {
            $('#billingAddress')[ $('#needsBillingAddress').is(':checked') ? 'show':'hide' ]();
        })();
        $('#needsBillingAddress').click( showHideBillingAddress );
    });
</script>

Here is a fiddle demonstrating this: http://jsfiddle.net/kQ3Hr/

B2K
  • 2,541
  • 1
  • 22
  • 34