0

I'm reading this part of Eloquent Javascript, and got stuck with the properties.

It said that

Both value.x and value[x] access a property on value—but not necessarily the same property.

......

Whereas value.x fetches the property of value named “x”, value[x] tries to evaluate the expression x and uses the result as the property name.

(value is an array and x is property like .length in this example.)

What's the difference between value.x and value[x]? I don't know how value[x] evaluate expression.

Community
  • 1
  • 1
chenghuayang
  • 1,424
  • 1
  • 17
  • 35
  • 2
    `value.x` means `x` in value. In the second one. `x` is a variable. So if x is equal to a then value[x] is equal to value.a – Downgoat Jun 09 '15 at 04:56
  • So it's like myArray.length === myArray[length] ? Which may be better to use usually? (like better efficiency in computing or human-friendly) – chenghuayang Jun 09 '15 at 05:04
  • 1
    myArray[length] is invalid unless you have a variable names "length" with the value of "length" dot notation is always better practice – Downgoat Jun 09 '15 at 05:05
  • 1
    `value.x` is same as `value['x']` just have a look at this simple example you will understand var a={'id':1, 'name':'xyz'}; console.log("a.id==", a.id, "a.name==", a.name) console.log("a['id']==", a['id'], "a['name']==", a['name']) if you will simply put `a[id]` , it will try to evaluate id and results in error `id is not defined` – shreyansh Jun 09 '15 at 05:10
  • Thanks all! One more to ask... for the answer already existed in another question, what does this mean: "The second advantage of square bracket notation is when dealing with variable property names." ? We can use custom variable `myControlNumber` for `myForm["myControlNumber" + i]`? – chenghuayang Jun 09 '15 at 05:25
  • @ChenghuaYang yes, you can – Downgoat Jun 09 '15 at 14:39

1 Answers1

3

I don't know how value[x] evaluate expression.

To evaluate an expression means to substitute all the symbols with corresponding values and apply all (if any) operations to them (and JS does everything for you so you should not think of it any hard ever).

In case of as trivial expression as just x - its evaluation equals to the value the variable x refers to.

Eg:

var x = 'vvv';
alert(value[x]);

In this example the vvv property of the value object will be alerted.

zerkms
  • 249,484
  • 69
  • 436
  • 539