Invalid shorthand property initializer ошибка js

I wrote the following code in JavaScript for a node project, but I ran into an error while testing a module. I’m not sure what the error means. Here’s my code:

var http = require('http');
// makes an http request
var makeRequest = function(message) {
 var options = {
  host: 'localhost',
  port = 8080,
  path : '/',
  method: 'POST'
 }
 // make request and execute function on recieveing response
 var request = http.request(options, function(response) {
  response.on('data', function(data) {
    console.log(data);
  });
 });
 request.write(message);
 request.end();
}
module.exports = makeRequest;

When I try to run this module, it throws the following error:

$ node make_request.js
/home/pallab/Desktop/make_request.js:8
    path = '/',
    ^^^^^^^^^^
SyntaxError: Invalid shorthand property initializer
    at Object.exports.runInThisContext (vm.js:76:16)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3

I dont quite get what this means, and what I can do to resolve this.

asked Feb 2, 2017 at 15:47

Pallab Ganguly's user avatar

Pallab GangulyPallab Ganguly

3,0132 gold badges10 silver badges9 bronze badges

Because it’s an object, the way to assign value to its properties is using :.

Change the = to : to fix the error.

var options = {
  host: 'localhost',
  port: 8080,
  path: '/',
  method: 'POST'
 }

Tobias's user avatar

Tobias

4,9407 gold badges34 silver badges40 bronze badges

answered Feb 2, 2017 at 15:49

Diego Faria's user avatar

Diego FariaDiego Faria

8,7553 gold badges25 silver badges33 bronze badges

4

use : instead of using = sign for fixing the error.

answered Mar 22, 2021 at 5:12

Ashwani Kumar Kushwaha's user avatar

Change the = to : to fix the error.

var makeRequest = function(message) {
 var options = {
  host: 'localhost',
  port : 8080,
  path : '/',
  method: 'POST'
 };

Bryan Boettcher's user avatar

answered Oct 22, 2020 at 5:37

amit paswan's user avatar

In options object you have used «=» sign to assign value to port but we have to use «:» to assign values to properties in object when using object literal to create an object i.e.»{}» ,these curly brackets. Even when you use function expression or create an object inside object you have to use «:» sign.
for e.g.:

    var rishabh = {
        class:"final year",
        roll:123,
        percent: function(marks1, marks2, marks3){
                      total = marks1 + marks2 + marks3;
                      this.percentage = total/3 }
                    };

john.percent(85,89,95);
console.log(rishabh.percentage);

here we have to use commas «,» after each property.
but you can use another style to create and initialize an object.

var john = new Object():
john.father = "raja";  //1st way to assign using dot operator
john["mother"] = "rani";// 2nd way to assign using brackets and key must be string

answered Mar 3, 2019 at 15:49

r.jain's user avatar

Use : instead of =

see the example below that gives an error

app.post('/mews', (req, res) => {
if (isValidMew(req.body)) {
    // insert into db
    const mew = {
        name = filter.clean(req.body.name.toString()),
        content = filter.clean(req.body.content.toString()),
        created: new Date()
    };

That gives Syntex Error: invalid shorthand proprty initializer.

Then i replace = with : that’s solve this error.

app.post('/mews', (req, res) => {
if (isValidMew(req.body)) {
    // insert into db
    const mew = {
        name: filter.clean(req.body.name.toString()),
        content: filter.clean(req.body.content.toString()),
        created: new Date()
    };

answered Dec 24, 2019 at 17:36

akshay_sushir's user avatar

“SyntaxError: Invalid shorthand property initializer” in JavaScript is a common error when creating a JavaScript object. Here’s a quick fix for this problem.

How does this error occur?

Scenario #1

In JavaScript, when we use the equals operator ‘=’ instead of a colon ‘:’ to separate the key-values (properties) in an object, the error “SyntaxError: incorrect shorthand property initializer” appears.

The following example triggers the “SyntaxError: Invalid shorthand property initializer”:

let Product = {
    name= 'Clothes Hanger',
    manufacturer= 'OEM',
    stock= 500
}

Error:

SyntaxError: Invalid shorthand property initializer

Scenario #2

Supposedly we declared an array of Products and a method to add new products to our array.

let Products = [
    {           
        id: 1,
        name: 'Clothes Hanger',
        manufacturer: 'OEM',
        stock: 400
    },
    {
        id: 2,
        name: 'Plastic Basket',
        manufacturer: 'OEM',
        stock: 700
    },
    {
        id: 3,
        name: 'Plastic Bucket',
        manufacturer: 'DuTa',
        stock: 100
    }
];

function add (name,manufacturer,stock){
    Products[Products.length]= {
        id = Products.length+1,
        name = name,
        manufacturer = manufacturer,
        stock = stock
    }
}

add ('Water Bottle','OEM',300);
console.log(Products);

The SyntaxError: Invalid Shorthand Property Initializer occurs.

We will suggest the solutions as the following.

Solution 1: Reassign the value to the object

An object in JavaScript has corresponding properties. A property of an object is a variable that is associated with the object. The only real difference between object properties and regular JavaScript variables is the relationship to objects. Its properties define the characteristics of an object. You can access an object’s properties using a straightforward dot-notation:

objectName.propertyName

The object name (which might be a regular variable) and property name, like other JavaScript variables, are case-sensitive. A property can be defined by having a value assigned to it as follows:

let Product = new Object ();
Product.name = 'Clothes Hanger';
Product.manufacturer = 'OEM';
Product.stock = 500;

Another way to assign an object’s properties is to include the key name as a string:

You may also access properties using a string value saved in a variable. The variable must be specified in brackets.

exp = 'Expiry';
Product[exp] = '2025';

Using this bracketed expression technique, the actual string, which is the name of the attribute, will be ‘Expiry’, not ‘exp’. It’s best to note this whenever you use dot annotation.

console.log(Product[exp]);
console.log(Product.Expiry);

Output

2025
2025

The same instance might alternatively be constructed using an “object initializer,” which is a curly-braced ({}) list of zero or more pairs of an object’s property names and associated values, separated by commas ():

let Product = {
    name: 'Clothes Hanger',
    manufacturer: 'OEM',
    stock: 500
}

Under the case where you use a function expression inside the object’s properties, you must also use the colon ‘:’

let Product = {
    name: 'Clothes Hanger',
    manufacturer: 'OEM',
    stock: 500,
    target: (stock) => stock/60
}

Solution 2: Change the way of declaration

The error occurs because ‘=’ is used instead of ‘:’ in the construction above.

To add a new key-value outside the braces, you can use assignment mark (=) as such:

let Product = {
    name: 'Clothes Hanger',
    manufacturer: 'OEM',
    stock: 500
}

Product.variant = 20;

To fix Scenario #2 problem, there are two ways to assign the values to your object in a function.

Our following examples will demonstrate each:

  • The literal object declaration:
function add (name,manufacturer,stock){
    Products[Products.length]= {
        id : Products.length+1,
        name : name,
        manufacturer : manufacturer,
        stock : stock
    }
}
  • The constructors:
function add (name,manufacturer,stock){
    //length = 3
    Products[Products.length]= new Object();

    // lenghth = 4 ; new Obj index =3
    Products[Products.length -1].id = Product.length;
    Products[Products.length -1].name = name;
    Products[Products.length -1].manufacturer = manufacturer;
    Products[Products.length -1].stock = stock;
}

Output

[
  { id: 1, name: 'Clothes Hanger', manufacturer: 'OEM', stock: 400 },
  { id: 2, name: 'Plastic Basket', manufacturer: 'OEM', stock: 700 },
  { id: 3, name: 'Plastic Bucket', manufacturer: 'DuTa', stock: 100 },
  { id: 4, name: 'Water Bottle', manufacturer: 'OEM', stock: 300 }
]
  • Class Object Constructor
function add (name,manufacturer,stock){
    newProduct = function (inputName,inputManufacturer,inputStock) {
            this.id = Products.length+1;
            this.name = inputName;
            this.manufacturer = inputManufacturer;
            this.stock = inputStock;
            }

    Products[Products.length]= new newProduct (name,manufacturer,stock);
}

Output

[
  { id: 1, name: 'Clothes Hanger', manufacturer: 'OEM', stock: 400 },
  { id: 2, name: 'Plastic Basket', manufacturer: 'OEM', stock: 700 },
  { id: 3, name: 'Plastic Bucket', manufacturer: 'DuTa', stock: 100 },
  newProduct {
    id: 4,
    name: 'Water Bottle',
    manufacturer: 'OEM',
    stock: 300
  }

This tutorial has mentioned initializers multiple times. For more ways to interact with objects, you may check out this document.

Summary

This article has covered all the information on resolving the invalid shorthand property initializer error in JS. The solution is straightforward, as demonstrated by the two examples above. Simply replace “=” with “:” and let the system handle the rest!

Maybe you are interested:

  • Invalid shorthand property initializer
  • Cannot convert undefined or null to Object in JavaScript
  • To load an ES module, set “type” – “module” in JavaScript

Tom

My name is Tom Joseph, and I work as a software engineer. I enjoy programming and passing on my experience. C, C++, JAVA, and Python are my strong programming languages that I can share with everyone. In addition, I have also developed projects using Javascript, html, css.

Job: Developer
Name of the university: UTC
Programming Languages: C, C++, Javascript, JAVA, python, html, css

Invalid shorthand property initializer is a common syntax error that you come across while you are doing object-oriented programming. This error occurs when we create an object.

Table of contents: – 

  1. Error
  2. Cause
  3. Solution
  4. Creating an object.
    1. Method 1
    2. Method 2
    3. Method 3
  5. The Conclusion

Let’s see an example of how this error occurs.


 const object = {
  name = 'John', 
  age = 34,
  id = 124,
  subject = 'English',
}

The following will be displayed in the console:


 SyntaxError: unknown: Invalid shorthand property initializer 

Cause 

This error occurs if you write equal to the operator (=) instead of colon (:) while assigning the value to the keys during the instantiation of the object.

Solution 

While declaring an object, we should use colons to separate the key-value pairs. Check the key-value pairs and replace the equals operator with a colon wherever necessary. The error will disappear.


 const object = {
  name: 'John', 
  age: 34,
  id: 124,
  subject: 'English',
}
console.log(object);

The following will be displayed in the console


{ name: 'John', age: 34, id: 124, subject: 'English' }

Creating an object 

Let’s check out the proper way of creating an object.

Objects can be variables so they can have many values. We write the values of each property of the object as key-value pairs separated by a colon. Objects are commonly declared using the const keyword. There are 3 ways of creating an object.

Method 1: If your object has only one property then use


 const obj = {
              name: "Harry"
              }

Each property contains a key and an associated value. Here, the name is the key, and “Harry” is the associated value

If your object has more than one property, then we write the keys along with their values separated by a comma (,). The following example demonstrates the method.

imageThe output of the above code will be as follows:

image

Method 2: You can create an object using the construct notation. First, create an empty object. Then, add the values of the properties using the dot notation or bracket notation (as per the requirement).Syntax


 objectName.propertyKey = specifiedValue;

Example


 const object = {};
      object.name = 'Rahul';
      object.id = '4562';
Method 3: Creating objects using the class constructor.First, we create a class and then create an instance of the class object. We will make use of the new constructor. The name of the class must have its first letter in uppercase while declaration.


 const Person = function (userName, userAge){
  this.name = userName;
  this.age = userAge;
  this.display = function(){
   console.log("The display output is"+ "nt name: " + this.name + "nt age: " + this.age);
  }
}
// create a new instance for the class-object
var myObject = new Person("John Thales",22);
  // call the display function  
  myObject.display();
  
  console.log( myObject );

The console will display the following:


 The display output is
 name: John Thales
 age: 22
{ name: 'John Thales', age: 22, display: [Function] }

However, if we add a new key-value pair to the object, you must use an equal sign.


 const object = {
  name : 'Selena', 
  age : 31,
  id : 154,
  subject : 'Physics',
  language: 'German'
}
object.country =  'India';
console.log(object);

The console will display:


{ name: 'Selena',
  age: 31,
  id: 154,
  subject: 'Physics',
  language: 'German',
  country: 'India' }

If you want to add a key that has spaces, special characters like #, @, & etc., or a hyphen, then you should use bracket notation instead of dot notation.


 const object = {
  name : 'Selena', 
  age : 31,
  id : 154,
  subject : 'Physics',
  language: 'German'
}
object['Email id'] =  '*Emails are not allowed*';

Conclusion

The “SyntaxError: unknown: Invalid shorthand property initializer” occurs when you add an equals operator instead of a colon for separating the key-value pairs while creating an instance for an object.

To fix this problem, make sure that you use a colon to separate the property from the value of the object. However, you can also try several other methods to create an object as discussed in the above article.

Syntaxerror: invalid shorthand property initializer error comes when we use equals operator rather than colon to separate key-values(properties) in object.

To resolve this issue, we need to use colon(:) rather than equals operator(=) between key and values of an object

Let’s see with the help of example:

const country = {

  name = ‘Bhutan’, // 👈️ need to use : and not =

  population = 3000,

}

Notice that we have used = between name and Bhutan.

To resolve this issue, use colon between key-value pair of an object.

const country = {

  name : ‘Bhutan’, // 👈️ Used : correctly

  population : 3000,

};

console.log(country);

{ name: ‘Bhutan’, population: 3000 }

To use new key-value property, you can use = sign.

const country = {

  name : ‘Bhutan’, // 👈️ Used : correctly

  population : 3000,

};

country.capital = ‘Thimphu’

console.log(country);

{ name: ‘Bhutan’, population: 3000, capital: ‘Thimphu’ }

Conclusion
To resolve Syntaxerror: invalid shorthand property initializer, use colon : to separate key-value pairs of object rather than equals operator(=).

That’s all about how to fix Syntaxerror: invalid shorthand property initializer.

Any site I visit in Chrome today, including Google.com, shows the following error in the console.log:

Uncaught SyntaxError: Invalid shorthand property initializer

The source shows as (unknown).
I wonder if I have a bad extension or something.
I’d rather not reset Chrome.
Are there any other troubleshooting tips?

asked Aug 10, 2017 at 22:37

Shawn's user avatar

This is caused by a recent chrome update. Somewhere in the chrome JSVM code they use a «=» where a «:» should be used to assign a value to an object’s property:

enter image description here

I think we have to wait for a patch or downgrade chrome.

EDIT: It seems to be something caused by the chrome developer tools:
https://stackoverflow.com/questions/17367560/chrome-development-tool-vm-file-from-javascript

Altough searching the dev tools code does not give any match either.

EDIT2: The answer of user gotoken seems to resolve the issue.

enter image description here

EDIT3: Seems that the solution of user gotoken is not a permanent one. Error reappears after some time. BetterHistory Extension needs to be patched.

answered Aug 11, 2017 at 7:31

Lucian Depold's user avatar

3

The answers are correct. However, I thought maybe a simple process answer would be helpful:

  1. In the address bar enter: chrome://extensions (Press enter to display your extensions.)
  2. The tab label should be «Extensions» and a list of your installed extensions should be on that page.
  3. Look for Better History. Should be near the top if your extensions are ordered by name.
  4. Click on the Enabled checkbox (the check mark should clear).
  5. Click on the Enabled checkbox again and the check mark should reappear.

That’s it. You will probably have to refresh the tab where you’re getting the error.

If this was too simple then please let me know.

Further. I found that this didn’t solve the problem once and for all. I’m using Vue and Webpack and found that the error eventually (generally after a few restarts) returns. Reset the enabled checkbox again and it goes away again. I guess we’re just going to have to live with it until the bug is fixed!

answered Aug 22, 2017 at 15:06

PhilMDev's user avatar

1

Понравилась статья? Поделить с друзьями:
  • Invalid procedure call or argument vba ошибка
  • Invalid price ошибка
  • Invalid outside procedure ошибка
  • Invalid or unqualified reference vba ошибка
  • Invalid number oracle ошибка