+ 1

How do you know when to use Square Brackets or dot notation?

5th May 2016, 2:44 PM
Daniel Lim
Daniel Lim - avatar
4 odpowiedzi
+ 1
I have run into the situation where lets say you have an array(or hash table) and you want to return the Xth item in the array. This won't work: var X = 3; return ary.X; But this will work: return ary[X];
9th Jun 2016, 7:19 PM
Dave Means
Dave Means - avatar
0
Consider the below example. var obj = {}; obj.name = 'VenomVendor'; obj['web site'] = 'VenomVendor.com'; // see space in key var x = 'runtime'; obj.x = 'X'; obj[x] = 'runtime';
12th Jun 2016, 11:22 AM
VenomVendor
0
You have a misconception: Array is not the same like an object. An array represents a list and an object represents a single thing. Arrays always require array[indexNumber] to access elements. Reason being that js will not accept keys starting with a number. The dot syntax to access an element only works on actual objects where the keys can start with some valid sign or letter. The only occurence where you have an array and a dot is when you use a property or a method of an array like array.length. Now to be complete. An array is an object too which is why there is a property array.length. To make it easy to understand: An array is a special object which only purpous is to manage a list of the same content easily.
24th Jul 2016, 2:03 PM
MarquisBs
MarquisBs - avatar
- 1
There is not a time when you should or shouldn't use it. It is very much preference. However, you should be consistent in whichever you choose.
6th May 2016, 1:38 AM
Jason