By LazioTibijczyk


2018-10-11 14:21:23 8 Comments

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?

4 comments

@Giorgos Papageorgiou 2018-10-11 14:30:01

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'
}

@Vaz 2018-10-11 14:28:16

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;

@Karim 2018-10-11 14:22:43

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.

@LazioTibijczyk 2018-10-11 14:23:24

Could I be anywhere closer to that? :D Thanks

@Karim 2018-10-11 14:24:00

you're welcome :)

@Steven Kampen 2018-10-11 14:22:35

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

Related Questions

Sponsored Content

6 Answered Questions

[SOLVED] What does (function($) {})(jQuery); mean?

  • 2010-05-30 01:36:57
  • Legend
  • 198322 View
  • 260 Score
  • 6 Answer
  • Tags:   javascript jquery

30 Answered Questions

[SOLVED] Function overloading in Javascript - Best practices

31 Answered Questions

[SOLVED] Is there a better way of writing v = (v == 0 ? 1 : 0);

12 Answered Questions

[SOLVED] JavaScript OR (||) variable assignment explanation

11 Answered Questions

[SOLVED] What's the most concise way to read query parameters in AngularJS?

  • 2012-06-16 13:03:52
  • Ellis Whitehead
  • 301937 View
  • 302 Score
  • 11 Answer
  • Tags:   angularjs ngroute

6 Answered Questions

[SOLVED] javascript set a variable if undefined

4 Answered Questions

[SOLVED] Chrome console clear assignment and variables

11 Answered Questions

[SOLVED] Redirecting to a certain route based on condition

  • 2012-07-18 12:44:22
  • st.never
  • 429002 View
  • 479 Score
  • 11 Answer
  • Tags:   angularjs ngroute

10 Answered Questions

[SOLVED] AngularJS : Initialize service with asynchronous data

4 Answered Questions

[SOLVED] Variable vs Parameter Scope and Assignment Values

  • 2014-01-14 19:35:15
  • HelloWorld
  • 164 View
  • 3 Score
  • 4 Answer
  • Tags:   javascript

Sponsored Content