For example: If I have something like user.email = email || user.email
I have to update the email property of user if email exists, otherwise leave it untouched.
With a mutation spell. Harry Potter has a few :)
A different take from ES6 , using a function and defaults applied.
let email = 'example@example.com';
checkEmail = ({userEmail = email})=>{
return userEmail;
}
checkOtherEmail = (userEmail = email)=>{
return userEmail;
}
checkEmail({userEmail = 'test@test.com'});
checkOtherEmail('test@test.com');
I guess there are different ways to do that, and all of them are valid. I prefer to use an if-statement:
if (email) {
user.email = email;
}
You could also use a setter (which you might even make very generic, so you could assign it to any object):
const user = {
email: undefined,
getEmail: () => this.email,
setEmail: email => { this.email = email || this.email; },
unsetEmail: () => { this.email = undefined; },
};
user.setEmail(email);
If you want to be extra careful (since above solutions might be dangerous in certain situations):
if (typeof email !== 'undefined') {
user.email = email;
}
// alternatively, using roption-js or similar,
// which adds Rust inspired Options
if (email.isSome()) {
user.email = email.unwrap();
}
function createUser(){
this._email = undefined;
};
Object.defineProperty(
createUser.prototype,
"email",
{
configurable:false,
enumerable:false,
get:function(){
return this._email;
},
set:function(v){
if (!this._email) {
this._email = v;
} else {
console.log("Email has been set already!!");
}
}
}
)
Then:
var user = new createUser();
user.email; //undefined
user.email = "some@email.com";
user.email; //"some@email.com";
user.email = "some2@email.com"; //"Email has been set already!!"
user.email; //"some@email.com";
I wrote a plain old style js, so that others can use it ie9+. Do your custom sanitization etc inside the set handler (also make the own _email property a getter/setter that works with a salt enclosed in an iife, so no other can set them). There are many many other ways to achieve similar stuff, this is one of them.
Matt Strom
Software Engineer, TypeScript ninja
If you're looking for terseness, then these will do the job, in addition to what you have:
email && user.email = email;(your linter will probably complain)
I myself would choose something similar to @ibowankenobi. I use TypeScript, so it's even easier since it will generate the necessary JavaScript for configuring properties:
export class User { private _email: string; get email() { return this._email; } set email(value: string) { if (value) { this._email = value; } } } const user = new User(); user.email = 'someone@email.com'; console.log(user.email) // someone@email.com user.email = ''; console.log(user.email) // someone@email.com