-1

is something like this possible in javascript?

maybe I have a variable (in this case its a number) that sometimes might be undefined. I'd like to sort of do some code right in the string to check the variable...

ps: I know that this throws throws an error!

var mystring='<b class="my string">'+(if(variable){variable;}else{0;})+'</b>';
Ben Muircroft
  • 2,936
  • 8
  • 39
  • 66
  • 1
    Have you looked at [inline conditionals](http://stackoverflow.com/questions/10270351/how-to-write-an-inline-if-statement-in-javascript)? – reto Jul 20 '13 at 14:39
  • 1
    Yes, you can do this in JS as people have illustrated below, but just because you can do this doesn't mean you should. Inserting logic within a string nested in a scoped variable isn't good practice. If you decide to write unit tests or even debug your code it can become very difficult. I would recommend keeping your logic and string assignment separate. – Scott Sword Jul 20 '13 at 14:47

4 Answers4

2

You can using the conditional operator (?:):

var
    variable = true,
    mystring = 'Hello, ' + ( variable ? 'world' : 'nobody' ) + '!'
;

JSFiddle demo.

James Donnelly
  • 126,410
  • 34
  • 208
  • 218
2

It seems the ternary operator ? will be of some use for you :

var like = true;

var myString = 'some string i ' +  ( (like) ? 'really' : 'do not' ) + ' like' ;
GameAlchemist
  • 18,995
  • 7
  • 36
  • 59
1

The typeof operator will specifically tell you if the variable is defined or not.

Link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

e.g.

var mystring = 'The variable ' + (typeof variable !== 'undefined' ? 'exists' : 'doesn\'t exist');

JSFiddle: http://jsfiddle.net/FlameTrap/AJfFk/1/

Josh
  • 2,835
  • 1
  • 21
  • 33
0

var mystring = '<b class="my string">' + ( typeof variable !== undefined ) ? 'variable' : 0 + '</b>';