0

I have JavaScript like this:

var myParam = 1;
var myVar = 'Lorem ipsum dolor [placeholder] amet';

I need to check, if myParam will be 1 then put inline of myVar - one else put there two. Something like this:

var myParam = 1;
var myVar = 'Lorem ipsum dolor '+ if (myParam == 1) return 'one' else return 'two' +' amet';

How to put IF/ELSE statement inside sting?

  • 1
    Please consider using `===` instead of `==`. If you know the type (Number or String) you can safely use `===`. – Halcyon Oct 22 '13 at 12:00
  • 3
    @FritsvanCampen I want to check if object has propery `value` like this: `myVar = 'some text '+ (typeof Obj.value != 'undefined' ? Obj.value : 'N/A') +' another text';` Which of these should I use `!=` or `!==` ?? –  Oct 22 '13 at 12:07
  • 2
    `typeof` will always return a string, and `'undefined'` is a string, so use `!==`. I have always claimed that there is never a valid reason to use `==` (or `!=`), if you know of one I'd love to hear about it :) – Halcyon Oct 22 '13 at 12:08
  • @FritsvanCampen and what is the difference? is there any matter of performance? –  Oct 22 '13 at 12:11
  • Yes, but I don't believe performance is the main reason, see: http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons – Halcyon Oct 22 '13 at 12:12
  • I got now. Thanks for advice. –  Oct 22 '13 at 12:14

4 Answers4

5

Use a ternary expression:

var myVar = 'Lorem ipsum dolor ' + (myParam == 1 ? 'one' : 'two') +' amet';
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
1

You can use ternary operator, where ?: operator can be used as a shortcut for an if...else statement.

Syntax: test ? expression1 : expression2

like

(myParam == 1) ?'one' : 'two'
Praveen
  • 55,303
  • 33
  • 133
  • 164
0

(myParam == 1) ? true : false;

You might want to think about === - or myParam could be 1, or "1", to use a basic example.

SpaceBison
  • 3,704
  • 1
  • 30
  • 44
-1

Using Ternary operator:

<condition> ? true: false

'Lorem ipsum dolor '+ ((myParam == 1) ? 'one' : 'two') +' amet';
Claudio Santos
  • 1,307
  • 13
  • 22