Matt Pierce
Matt Pierce

Reputation: 805

Nested If Statement Inside Javascript Variable

I have a javascript variable that is a consolidation of many different lines of text (html markup). See below. the info from the image property of the data object I'm injecting into this function may or may not be blank. So, I want a basic if statement to check if it is blank and output some other text if it is.

function(data) {

    var div = [
        <a href="/profile/'+data.message.name+'">',
            if (data.message.image == "") {
                // Some other string
            }
            <img src="/images/profiles/'+data.message.image+'" alt="#"/>',
        </a>',  
    ].join('');
}

Is it possible to nest an If statement in a variable like this? If so, what's the proper syntax?

Thanks!

Upvotes: 0

Views: 101

Answers (3)

Gomzy
Gomzy

Reputation: 431

Conditional (Ternary) Operator

JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.

Syntax

variablename = (condition) ? value1:value2 

Upvotes: 1

Rayon
Rayon

Reputation: 36599

"" will be falsey value hence you could try the same using || operators.

Try this:

function test(data) {
  var image = 'Some other string';
  var div = [
    '<a href="/profile/' + data.message.name + '">',
    '<img src="/images/profiles/' + (data.message.image || image) + '" alt="#"/>',
    '</a>'
  ].join('');
  alert(div);
}
test({
  message: {
    name: 'Test Name',
    image: ''
  }
});

Upvotes: 0

Aniket Bhange
Aniket Bhange

Reputation: 55

I don't know for what you want to write this kind of code you can use Jquery append method for your solution.

For your code this will work

div = []
div.push '<a href="/profile/'+data.message.name+'">'
if data.message.image == ""
    //do something
    div.push "someting"
div.push '<img src="/images/profiles/'+data.message.image+'" alt="#"/>'
div.push '</a>'
div.join('')

This code is written in coffee but you will understand it.

Upvotes: 0

Related Questions