javascript object property cannot be defined - javascript

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']='incopraveen#gmail.com';
alert(User.email); //says email is not defined.
NB: I have tried removing semicolons also.
Tried dot notation also

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 = "test#example.com";
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: "test#example.com",
};

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']='incopraveen#gmail.com';
This link could help you, https://alligator.io/js/object-property-shorthand-es6/

Related

How do i create an incrementing array of objects, User1, User2 etc. with object values attached to each entry?

Trying to get an array of temporary users, where next user should be "user" + ArrayOfUsers.length, but i have no idea of how to get there, even after 2 hours of googleing.
Each user in the array should be attached with object values of my standard user defined like this.
function user(name, email, code){
this.name = name;
this.email = email;
this.code = code;
}
Javascript doesn't support declaring variables with dynamic names...But you can assign a dynamic key to a window object (or any other object), and access them as variable names (Only applicable for keys set to window object).
Please note that this won't work in strict mode use strict.
And I'm not sure why you want it as a dynamic variable. Anyways you could do it like below.
You could keep a count variable and set variable to window object using
this["user"+index] = newUser;
Try the below snippet...
function user(name, email, code) {
this.name = name;
this.email = email;
this.code = code;
}
var index = 0;
function createUser(name, email,code){
const newUser = new user(name, email, code);
this["user"+index] = newUser;
index++;
return newUser;
}
createUser("a", "a#a.com", 1);
createUser("b", "b#b.com", 2)
for(let i = 0; i< index; i++){
console.log(this["user"+ i]);
}
console.log(user0);
console.log(user1);

admin.attributes.isAdmin is assigned value. while guest.attributes.isAdmin is assigned nothing . Please let me understand it

I am trying to understand this code snipped:
var User = function() {};
User.prototype.attributes = {
isAdmin: false
};
var admin = new User("Sam"),
guest = new User("Bob");
admin.attributes.isAdmin = true;
alert(admin.attributes.isAdmin);
alert(guest.attributes.isAdmin);
its output will be true (twice)
Kindly help me out in understanding the concept. Any help is mush appreciated.
Thank you
You could use a copy of attributes, because by addressing attributes, you overwrite the value for all instances.
var User = function() {
this.attributes = Object.assign({}, this.attributes);
};
User.prototype.attributes = { isAdmin: false };
var admin = new User("Sam"),
guest = new User("Bob");
admin.attributes.isAdmin = true;
console.log(admin.attributes.isAdmin);
console.log(guest.attributes.isAdmin);
Javascript takes a property and looks if it exits. If not, it looks in the prototype chain if the property exist here. If it exist, it take this value.
Same goes for assigning a value.
Fo a more detailed view, you may vistit Inheritance and the prototype chain
In JS objects are passed by reference. In your exampleadmin and guest store references to the same object attributes. You could clone the object (create a copy of it's values) or store the isAdmin property in the prototype.

Using classes in for loop in node.js

To be honest, I don't know what to ask for my case so I'll just add some details. I come from java so I am familiar with classes.
Let's take for instance a class and for making it easy, drop the private fields to public and no getter and setter
class User{
public String name;
public String email;
}
This is useful in certain cases, for instance have an array of users and then I can use something like:
for(User user: usersList){
user.name='some new value'
//since user is a class, code assist, suggests the name and also if I have user.namee it throws an error
}
Now moving into javascript, I can obtain an array and do something like
for (let user of usersList){
user.name='some new value'
//however if I type user.nammee no error is thrown and code assist does not know what to recomment
}
I think that now you may get the idea. I want it to make it easier to properly obtain the object fields with code assist and also avoid typing errors because of property name badly typed. Javascript classes from what I see have only methods... so what can I apply in this case?
check out Typescript
and this "fiddle" on the TypeScript Playground
class User {
constructor(public name: string, public email: string = "") { }
/*
//shorthand for
public name: string;
public email: string;
constructor(name:string, email:string="") {
this.name = name;
this.email = email;
}
*/
}
var usersList = [
new User("Jack"),
new User("Jill"),
new User("Joe")
];
for (let user of usersList) {
user.email = user.name + "#mail.com";
}
and since userList is recognized as type User[], let user is also typed as let user:User
JavaScript allows to reference properties which an object does not have: you can add them ad-hoc, and if you read non-existing properties, you just get undefined. This is how JavaScript works.
If you want to get an error when you try to assign to a non-existing property, then consider using the Object.seal method, which you could apply in the constructor for your class:
"use strict";
class User{
constructor (name, email) {
this.name = name;
this.email = email;
// Seal will disallow new properties
Object.seal(this);
}
}
const user = new User();
user.name = "Jeff";
console.log(user); // Shows property with "Jeff"
user.nammmeeee = "Jeff"; // Produces error
Make sure to use strict mode ("use strict") as otherwise these errors are suppressed.
You can do this in javascript. Just that, your userslist will be array in which you will have your users. Loop will be for loop from 0 to length-1. This class will have some syntax like this.
var userclass = {
Name:'xyz',
Addr:'address',
.....other props
}

Define two objects with the same name in javascript

Is it possible to define two objects with the same name in javascript..
for example
var record = {
id: some value,
name: some value,
subject: some value,
};
and again
var record = {};
No and Yes
No if is global variable or you insert in the same group example:
if(){
var record = {
id: some value,
name: some value,
subject: some value,
};
var record = {};
}
Yes If you make local variable or insert in diferent groups like:
if(){
var record = {
id: some value,
name: some value,
subject: some value,
};
} else {
var record = {};
}
In JavaScript, a variable can be declared after it has been used.
In other words; a variable can be used before it has been declared.
You can declare a uniquie variable only in a scope. you must read java-script hoisting:
http://www.w3schools.com/js/js_hoisting.asp

Separating truthy and falsey values from an object

I'm working on a java challenge that reads
//In the function below you'll be passed a user object. Loop through the user object checking to make sure that each value is truthy. If it's not truthy, remove it from the object. Then return the object. hint: 'delete'.
function truthyObjLoop(user) {
//code here
I came up with....
var user = {};
user.name = {};
user.age = {};
if (user !== false)
{
return user;
} else {
delete user;
}
}
However whenever I try it it comes back with the error Function returned
{"name":{},"age":{}}
instead of
{"name":"ernest","age":50}
when passed
{"name":"ernest","age":50,"funky":false}....
Can anyone help me understand why this is happening or if I'm using the wrong symbols here? Thank you.
var user = {};
user.name = {};
user.age = {};
The user name and age should be the values, not Objects. curly braces mentions objects, you are wrong.try my following code please
var user = {};
user.name = "john";
user.age = 12;
Also read this tutorial please :
http://www.w3schools.com/json/
The text says "you'll be passed a user object". That means the user is being defined outside of the function, and passed in. Here's what you're looking for:
function truthyObjLoop(user) {
for (var k in user) {
if (!user[k]) delete user[k]
}
console.log(user);
}
You then should pass in a "user" with all sorts of different attributes to demonstrate how the test works:
var person = {
age: 29,
gender: "male",
pets: [
{
type: "cat",
name: "smelly"
}
],
children: 0,
married: false
};
truthyObjLoop(person);
Here's a jsfiddle:
https://jsfiddle.net/mckinleymedia/tb823pyp/
Notice it removes the attributes with a value of 'false' or '0'.

Categories

Resources