when I have an array a = [1,2,3];
and when I invoke method a.length
- is the engine counting it's length every time or is it cached - and when object is changed it's removed and counted once again upon invocation or is it happening every time from start to finish? Does anyone know how it is counted?
Asked
Active
Viewed 55 times
1

Bergi
- 630,263
- 148
- 957
- 1,375

CptDolphin
- 404
- 7
- 23
-
this is probably implementation dependant, and it shouldn't /really/ affect how you write your code :) +1 for interesting question, though. – iPhoenix Dec 15 '19 at 14:36
-
`.length` is not a method. It's a property. (It could be backed by a getter/setter though, that is indeed implementation-dependant) – Bergi Dec 15 '19 at 14:38
-
1It does not get counted every time you access it. It will change, if you change the array, but in sometimes perhaps unintuitive ways (it must always be greater than the highest array-index property, but not exactly +1. E.g. deleting the highest array element will not change the length. Adding one, which is higher, than the highest, will). – ASDFGerte Dec 15 '19 at 14:40
-
Examples for the above mentioned: "deletion does not change length": `let arr = [0, 1]; let oldLength = arr.length; delete arr[1]; console.log(oldLength === arr.length);`, "adding higher properties does change length": `let arr = [0, 1]; let oldLength = arr.length; arr[2] = 2; console.log(oldLength < arr.length);`. Note that other means of deletion may update the `length`, e.g. `splice` will. Also note, that `length` is assignable, and the above rules directly imply, that e.g. the assignment `arr.length = 0` actually deletes properties. – ASDFGerte Dec 15 '19 at 14:49