Reputation: 1957
I would like to know a simplest and best way to assign a value to a variable if other variable is not null/undefined. This isn't the shortest and most elegant way possible
var name = 'Bob'
var surname = '';
if(name) {
surname = 'The builder'
}
What I'd rather like to do is something like
var surname = if(name) ? 'The builder' : '';
Is this possible somehow?
Upvotes: 2
Views: 1451
Reputation: 604
Actually you can have it in this format and omit the else statement.
var surname = names && 'The builder';
It is basically equal to
if(name) {
surname = 'The builder'
}
Upvotes: -1
Reputation: 434
Unlike other answers, this way, you change the surname
value, only if the tested condition is true
.
This means, that you don't have to repeat (and hardcode) the surname
original value. (i.e. ''
)
var name = 'Bob';
var surname = '';
surname = name ? 'The builder' : surname;
Upvotes: -1