2

I am creating an array by two way.

  • my first way is creating an array normally
  • my second way is creating an array by using backticks function

let array=["1234"];

function createArrayByBakticks(obj)
{
return obj;
}

let backtickArray = createArrayByBakticks `1234`;// it's responding an array

console.log(array); //1st way and it returns an array 
console.log(backtickArray ); //2nd way and it returns a same array 

backtickArray.push(1);// but it's throwing an error while push a new value. 

// Error: Uncaught TypeError: Cannot add property 1, object is not extensible


console.log(backtickArray);

Above both ways are return as a array data. But the second array is not supporting inbuilt function of array which is generated by back-ticks. WHY? And what is the difference between in the both ways?

CBroe
  • 91,630
  • 14
  • 92
  • 150
Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234

2 Answers2

2

createArrayByBakticks is used as a so-called tag function. The first argument passed to the function is an array containing all strings of the template literal.

If you dive deep into the language specification, section 12.2.9.3, then you will see the following step is performed after the array has been created:

  1. Perform SetIntegrityLevel(template, "frozen").

This means that in your case objis frozen and no property can be added. That's why invoking push doesn't work.

You can confirm this by calling console.log(Object.isFrozen(backtickArray)).

a better oliver
  • 26,330
  • 2
  • 58
  • 66
1

The array returns from the function by value, meaning it's immutable.

If you use concat, you'll get a new copy of it, which you can modify:

let array = ["1234"];

function createArrayByBakticks(obj) {
  return obj;
}

let backtickArray = createArrayByBakticks `1234`; // it's responding an array

console.log(array); //1st way and it returns an array 
console.log(backtickArray); //2nd way and it returns a same array 

let newArray = backtickArray.concat(1); // a new mutable array is generated
newArray.push(2);                       // so you can even keep modifying it
console.log(newArray);
GalAbra
  • 5,048
  • 4
  • 23
  • 42