Home > Enterprise >  When are array literals created?
When are array literals created?

Time:12-22

I was reading MDN documentation, and i cant understand below statement about array literal.

MDN Array literals

If an array is created using a literal in a top-level script, JavaScript interprets the array each time it evaluates the expression containing the array literal. In addition, a literal used in a function is created each time the function is called.

CodePudding user response:

This means that:

const arr = [1, 2, 3];

will create a new array each case the statement is executed, as opposed to reusing the same array over and over.

This matters because an array is mutable in JS. See the below code:

function list() {
  return [1, 2, 3];
}

const arr = list();
arr[0] = 42;
console.log(list());

Without the specification you quoted, the second line could output [42, 2, 3].

On this topic, caml comes to my mind. In this language, string literals are allocated only once. This saves memory, but as string are mutables (in caml), you can observe the above behavior.

CodePudding user response:

The array literals are just syntactic sugar over new Array(). So, naturally, a new array object would be created as many times as the function it is in will be called. It also has to do with the fact that once a function (frame) is popped of the call stack all the variables that were stored in its scope (lexical environment) would simply be destroyed (garbage collected), unless of course they were not declared inside this function's scope which would not trigger a creation of a new array or any other object created with literal syntax for that matter in the first place.

  • Related