Reputation:
I have declared an object in JS and trying to assign a value to its properties. But I can do it when only one property is defined, but not with more than one property.
This works fine:
let User = {
name
};
User['name']='Praveen';
alert(User.name);
But this does not
let User = {
name,
email
};
User['name']='Praveen';
User['email']='[email protected]';
alert(User.email); //says email is not defined.
NB: I have tried removing semicolons also. Tried dot notation also
Upvotes: 0
Views: 116
Reputation: 1055
Your code is ok,
Please check do you have any existing name,email
variable which you are set in the User Object,
I think you do not have existing name and email variable. So that It can not create the User Object itself.
You can do like this..
let User = {};
User['name']='Praveen';
User['email']='[email protected]';
This link could help you, https://alligator.io/js/object-property-shorthand-es6/
Upvotes: 0
Reputation: 138257
Because this:
let User = {
name,
email
};
is a shortform for:
let User = {
name: name,
email: email,
};
So it directly initializes both properties to the value that the variables name
and email
are holding. name
is defined, it is the name of the page you are in, which you can easily check with:
console.log(name);
but email is not defined yet, and trying to get an undeclared variable results in an error:
console.log(email); // email is not defined
To solve that, explicitly declare both variables before:
let name = "test";
let email = "[email protected]";
let User = {
name,
email
};
Or initialize the properties not at all:
let User = {};
or directly set the properties to a value:
let User = {
name: "test",
email: "[email protected]",
};
Upvotes: 5