LazioTibijczyk
LazioTibijczyk

Reputation: 1957

Simplest way to assign value to a variable based on a condition

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

Answers (4)

Giorgos Papageorgiou
Giorgos Papageorgiou

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

Tin
Tin

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

Karim
Karim

Reputation: 8642

the ternary operator

var surname = name ? 'The builder' : '';

if name is a truthy value surname will be equal to the string 'the builder', otherwise will be assigned to an empty string.

Upvotes: 3

Steven Kampen
Steven Kampen

Reputation: 631

var surname = name ? 'The builder' : '';

Upvotes: 3

Related Questions