-1

In Javascript it is possible to use a number (integer) or a string (or a char) to index an array for example:

array[0] = true;

or

array['0'] = true;

Does the computer memory work different depending on how you index the array or is it the exact same thing to do it both ways?

I'm not human
  • 544
  • 1
  • 9
  • 30

4 Answers4

1

The indexes are stored internally as strings.
But it's more common practise to use numbers to access an array by it's index.

A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 2^³²−1

It's explained in this old post

Below is a snippet that showcases it.
Accessing the index with a string works fine as long that index string only contains digits.
But by expressing the index as a word then it can only be accessed with that word. And console logging the array doesn't show it.

let arr = [0,'a one','a two','a three'];
arr['four'] = 'a four';
arr.push('5');
arr.push(6);
arr.push([7,'7']);
arr.push({a:8, b:'8'});


console.log('\nLog the array:\n\n');
console.log(arr);

console.log('\nAccessing the array:\n\n');
console.log("arr[0]:\t" + arr[0]);
console.log("arr[\'1\']:\t" + arr['1']);
console.log("arr[\'two\']:\t" + arr['two']);
let i=2;
console.log("arr[++i]:\t" + arr[++i]);
console.log("arr[\'four\']:\t" + arr['four']);
console.log('arr[4]:\t'+ arr[4]);
console.log('arr[5]:\t'+ arr[5]);

console.log('\nListing the types in the array:\n\n');
for (var a in arr) console.log(a+'\tindex type: '+ typeof a +', value: '+ arr[a] + ', value type: '+ typeof arr[a]);

And here's a snippet to compare speed between using a number or a string in your browser. It should take roughly the same time.

let arr1 = [];
console.time('Access array through string');
for(let i = 0; i <= 42000000;i++){
 arr1['42000000'] = 42;
}
console.timeEnd('Access array through string');

let arr2 = [];
console.time('Access array through integer');
for(let i = 0; i <= 42000000;i++){
 arr2[42000000] = 42;
}
console.timeEnd('Access array through integer');
LukStorms
  • 28,916
  • 5
  • 31
  • 45
1

The answer is simple: there is no difference.

Javascript arrays are objects. All keys of objects are strings (or symbols), but never numbers.

Property names must be strings. This means that non-string objects cannot be used as keys in the object. Any non-string object, including a number, is typecasted into a string via the toString method. ...see more here

The property accessor [] converts to string first before looking for the property. (some engines may optimize this step and not perform a proper toString call, but it's of no concern here)

So array[0] is interpreted as array['0'].

const a = {
    toString: function () {
        console.log("a.toString called")
        return "1";
    }
};

const array = ['a','b','c'];
console.log(array[a]);
RaphaMex
  • 2,781
  • 1
  • 14
  • 30
0

When you use quotations for indexing, you're creating a key-value pair in the array. I recommended you stick to numerical notation unless you're intentionally creating those pairs; while array['0'] technically posts to the position, it's bad practice.

Even though myArr['two'] doesn't seem to want to show up in the snippet output, if you hit F12 and look at the console output, you'll clearly see it displayed.

["String 0", "String 1", two: "String 2"]

let myArr = [];
myArr[0] = "String 0";
myArr['1'] = "String 1";
myArr['two'] = "String 2";

console.log(myArr);
Epoch
  • 656
  • 4
  • 16
0

As the mdn docs state, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

Arrays are actually just objects that have array-like properties. Keys in JavaScript are strings. So when you see an array, it's actually just a set of key-value pairs, where the keys are index numbers.

Arrays are a special data type. Adding keys that do not correlate to possible indexes are added to an 'object property collection' and are not returned when you use the object.

I think the chrome console does the best job of displaying this:

This array is actually an object with keys of 0 1 2 3, a length property, and a prototype.

enter image description here

Andrew
  • 7,201
  • 5
  • 25
  • 34