How to ignore using variable name as a literal while using push() in JavaScript?


To avoid using variable name as a literal, use square brackets. Following is the code −

Example

var name = "David"
var putTheAllData = []
putTheAllData.push( { name: "The name is name will remain same" } )
putTheAllData.push( { [name]: "The name is David will be changed [name]"} )
console.log(putTheAllData);

To run the above program, you need to use the following command −

node fileName.js.

Output

Here, my file name is demo166.js. This will produce the following output −

PS C:\Users\Amit\javascript-code> node demo166.js
[
   { name: 'The name is name will remain same' },
   { David: 'The name is David will be changed [name]' }
]

Updated on: 12-Sep-2020

149 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements