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

To avoid using a variable name as a literal string when pushing objects to an array, use square brackets [variableName] for computed property names. This allows the variable's value to become the property key.

The Problem with Literal Property Names

When you use name: value in an object, "name" becomes a literal string property, not the variable's value:

var name = "David";
var data = [];

// This creates a property literally named "name"
data.push({ name: "This will always be 'name' property" });
console.log(data);
[ { name: 'This will always be 'name' property' } ]

Solution: Using Computed Property Names

Use square brackets [variableName] to use the variable's value as the property key:

var name = "David";
var putTheAllData = [];

// Literal property name - "name" as string
putTheAllData.push({ name: "The property key is literally 'name'" });

// Computed property name - uses variable's value
putTheAllData.push({ [name]: "The property key is the value of variable 'name'" });

console.log(putTheAllData);
[
  { name: 'The property key is literally 'name'' },
  { David: 'The property key is the value of variable 'name'' }
]

Multiple Variables Example

var firstName = "John";
var lastName = "Smith";
var age = "25";

var userData = [];

// Using computed property names for all variables
userData.push({ [firstName]: "First name value" });
userData.push({ [lastName]: "Last name value" });
userData.push({ [age]: "Age value" });

console.log(userData);
[
  { John: 'First name value' },
  { Smith: 'Last name value' },
  { '25': 'Age value' }
]

Comparison

Method Syntax Property Key
Literal { name: value } String "name"
Computed { [name]: value } Variable's value

Conclusion

Use square brackets [variableName] for computed property names when you want the variable's value as the property key, not the variable name itself. This ES6 feature provides dynamic object property creation.

Updated on: 2026-03-15T23:18:59+05:30

284 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements