“Invalid Shorthand Property Initializer” Error In JavaScript – How To Fix?

Invalid shorthand property initializer

The “Invalid shorthand property initializer” error often occurs when assigning a value to an object property. Fortunately, this is usually very simple to fix. Please check our tutorial below to deal with it properly.

What causes the “Invalid shorthand property initializer” error in JavaScript?

Reproduce the error

Let’s take a look at example 1:

const person_1 = {
  name: 'Kai', 
  age: 21,
  gender: 'male',
  email: '[email protected]',
  job: 'student',
  address: '123abc'
}

const person_2 = {
  name: 'David', 
  age: 32,
  gender: 'male',
  email: '[email protected]',
  job: 'teacher',
  address: '456xyz'
}

const person_3 = {
  name = 'Emma', 
  age: 25,
  gender: 'female',
  email: '[email protected]',
  job: 'artist',
  address: '789mnp'
}

console.log(person_3.name);

Output: 

SyntaxError: Invalid shorthand property initializer

At first glance, there seems to be no problem with our program. But if we take a closer look at our code, in line 20, it should be a colon instead of an equal sign. And this is the reason for our error.

How to solve this error?

You can use a colon instead of an equal sign to solve the error.

When we assign a value to a variable, we can use the equal sign:

const obj_1 = ‘apple’; 
const obj_2 = ‘orange’;
const obj_3 = ‘peach’;

Objects are also variables but contain many values. If we want to assign a value to an object’s property, we have to use a colon:

name:value

Example: 

const apple = {
  color: 'Red',
  size: 'small',
  quantity: 14
}

Fixed code for example 1:

const person_1 = {
  name: 'Kai', 
  age: 21,
  gender: 'male',
  email: '[email protected]',
  job: 'student',
  address: '123abc'
}

const person_2 = {
  name: 'David', 
  age: 32,
  gender: 'male',
  email: '[email protected]',
  job: 'teacher',
  address: '456xyz'
}

const person_3 = {
  name: 'Emma', 
  age: 25,
  gender: 'female',
  email: '[email protected]',
  job: 'artist',
  address: '789mnp'
}

console.log(person_3.name);

Output: 

Emma

But if we want to add a property to an existing object, we can use an equal sign: 

const person_1 = {
  name: 'Kai', 
  age: 21,
  gender: 'male',
  email: '[email protected]',
  job: 'student',
  address: '123abc'
}

person_1.id = 123
console.log(person_1.id);

Output: 

123

Summary

The “Invalid shorthand property initializererror is common in JavaScript and often related to how we assign value to an object’s property. To avoid this problem, ensure to use a colon instead of an equal sign.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *