Normal arrays and arrays generated by back-ticks both serve the same purpose of storing multiple values

There are two methods I am using to create an array.

  • The first method involves creating an array in a traditional way.
  • The second method involves creating an array 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 the same array 

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

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


console.log(backtickArray);

Both of the methods mentioned above return data as an array. However, the second array created by backticks does not support the built-in functions of arrays. WHY? What is the difference between these two methods??

Answer №1

generateArrayWithBackticks serves as a special tag function. The initial parameter passed to this function is an array that holds all the strings from the template literal.

If you delve into the intricacies of the language specification, particularly outlined in section 12.2.9.3, it reveals a critical step taken after the formation of the array:

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

This indicates that in your scenario, obj has been frozen, preventing any additional properties from being added. Hence, attempting to use push will be futile.

You can validate this by utilizing

console.log(Object.isFrozen(backtickArray))
.

Answer №2

When the function is called, the array is returned by value, making it immutable.

By using the concat method, a new copy of the array is created, allowing for modifications:

let array = ["1234"];

function createArrayByBakticks(obj) {
  return obj;
}

let backtickArray = createArrayByBakticks `1234`; // produces an array

console.log(array); // First way, returning an array
console.log(backtickArray); // Second way, also returning the same array

let newArray = backtickArray.concat(1); // generates a new mutable array
newArray.push(2);                       // enabling further modification
console.log(newArray);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

retrieving the values listed on the current v-data-table page

In my vuejs2 project, I am utilizing a v-data-table to display information in columns about a large number of users. Each page shows 25 users, with a total exceeding 60,000 individuals. I am wondering if there is a way to retrieve the list of users curre ...

Utilize CSS to format the output of a script embedded within

When I embed the following script in my HTML, the output doesn't have any styling. How can I style the script output to blend well with the existing HTML structure? I tried accessing the output by ID, but couldn't figure it out. <script> ...

How can TypeScript be used to enable CSV or PDF export in a material-react-table?

Is it possible to incorporate the ability to export data to CSV or PDF in a material-react-table? While I am familiar with how to do this with a Material UI table, I have not been able to find the same functionality for the material-react-table. Thank you ...

Are Json files a reliable choice for storing data in Next.js applications?

I'm currently working on developing a video application that will offer both free and premium videos. With approximately 100 videos in the pipeline, I am contemplating whether setting up a database to store video links is necessary. Considering securi ...

Instead of using a `thisArg`, consider employing a closure when encountering problems with .pipe(map

The code I currently have is showing as deprecated. I am in need of assistance to update it, particularly the map section. There is an issue with the map part that needs attention. /** @deprecated Use a closure instead of a thisArg. Signatures accepting ...

Issues arising with carousel pager in Cycle2 slideshow not functional

Our unique pager is designed with the "Advanced Custom Template" on a dynamic carousel slideshow. Everything seems to be running smoothly until I interact with the pager - then things start acting strangely. The active slide doesn't change position a ...

How to use the v-model to round up a number in Vue.js

I need to round up a number in my input field: <b-form-input id="amount_input" type="number" v-model="Math.ceil(form.contract.reward_cents / 100)" :state="validate(form.contract.reward_cents)"/> ...

The build process encountered an error due to the absence of ESLint configuration after the import

Having recently worked on a Vue project created using Vue CLI, I found that eslint was also included in the project. Although I haven't utilized eslint much up to this point, I understand that it is beneficial for catching stylistic errors, semantic e ...

Leveraging underscore.js for null verification

let name = "someName"; if(name !== null) { // perform some action } Currently, I am utilizing http://underscorejs.org/#isNull. How can I achieve the same functionality using underscore.js? Is there any noticeable performance enhance ...

Having trouble loading and viewing large PDF files using XMLHttpRequest

I'm currently using a straightforward XMLHttpRequest to communicate with a PHP server script. fxhr.onload = function (data) { //console.log(JSON.parse(data.target.response)); var string = JSON.parse(data.target.response).data.content; ...

Storing events from FullCalendar into a database

I have been working on implementing the following markup: Within my project, I am using a fullcalendar instance. When a user clicks on a day, it triggers the dayClick callback function which opens a bootstrap modal. The user can then enter a title, start/ ...

Incorporating additional properties into a TypeScript interface for a stateless, functional component within a React Native application

When following the React Native documentation for consistent styling, a recommendation is made to create a <CustomText /> text component that encapsulates the native <Text /> component. Although this task seems simple enough, I'm facing d ...

Storing information retrieved from firestore for safekeeping

I am having trouble figuring out how to save data from Firestore. I attempted saving it using this.favLists so that I wouldn't have to send requests each time I make a request. export default defineComponent({ data() { return{ favLists: '&a ...

Transform the bash array into JSON format and save it to a file

I have a bash array containing strings that I need to convert to JSON and then write to a file. Let's assume the array looks like this: my_strings=("hello" "world") I was able to successfully convert it to JSON format and write to file by using the f ...

Text in a website displayed in a 3D perspective fashion

Is there a way to create 3D text effects with perspective using a combination of Javascript and CSS? I am open to suggestions that involve the use of external libraries for Javascript or CSS as well. ...

the transparency feature in three.js is completely malfunctioning

I've been browsing through some questions that have already been asked by others here, and one that caught my attention is: Transparent background with three.js I am struggling to make the background transparent instead of black as described in the ...

Is there a way to utilize vue.js and multer for uploading multiple files simultaneously?

I am facing an issue with multer where I can upload a single file successfully, but when attempting to upload multiple files it does not work and no files are captured by multer. I am using formData.append() to send files, but it only manages to upload a ...

Error message: "Unidentified variable in the code snippet from MUIv5 sample."

Achieving the Objective To implement a drawer sidebar in MUI5 that can be toggled open and closed by the user, I am exploring the documentation for the Drawer component as well as referencing an example. Encountering an Issue Upon copying the code from ...

An unexpected 'foo' key was discovered in the current state being processed by the reducer when using redux-toolkit's configure store and a customized store enhancer

I've been working on developing a custom store enhancer to add new values to my root state. However, I've encountered an unexpected key error after delving into the complexities of custom enhancers. While I can see the new state part in devtools ...

execute a function when an image is clicked using jQuery

How can I create an onclick event for the variable imageCatuaba? function setCatuaba(map) { var imageCatuaba = { url: 'images/catuskov.1.png', origin: new google.maps.Point(0, 0), anchor: new google.maps.Point(0, 32) }; I'm ...