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?

6
  • 1
    Please consider using === instead of ==. If you know the type (Number or String) you can safely use ===. Commented Oct 22, 2013 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 !== ?? Commented Oct 22, 2013 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 :) Commented Oct 22, 2013 at 12:08
  • @FritsvanCampen and what is the difference? is there any matter of performance? Commented Oct 22, 2013 at 12:11
  • Yes, but I don't believe performance is the main reason, see: stackoverflow.com/questions/359494/… Commented Oct 22, 2013 at 12:12

4 Answers 4

5

Use a ternary expression:

var myVar = 'Lorem ipsum dolor ' + (myParam == 1 ? 'one' : 'two') +' amet';
Sign up to request clarification or add additional context in comments.

Comments

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'

Comments

0

(myParam == 1) ? true : false;

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

Comments

-1

Using Ternary operator:

<condition> ? true: false

'Lorem ipsum dolor '+ ((myParam == 1) ? 'one' : 'two') +' amet';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.