Search code examples
javascriptjquerychainingternary

Ternary operation of an incomplete statement


Syntax question; is it possible to do the following:

var home_page_feed;
var videos = $get_utoob_videos;
for each(video in videos) {
    if(video.special_interests)
        $(home_page_feed).prepend(video.thumbnail);
    else
        $(home_page_feed).append(video.censornail);
}

...but in a single ternary operation, like this:

for each(video in videos)
    $(home_page_feed) .CHAIN. 
        video.special_interests ? 
             // true - chain this
            .prepend(video.thumbnail) :
             // false - chain this instead
            .append(video.censornail);

I put .CHAIN. as a placeholder. Is there a jQuery function that would chain to a incomplete statement by means of ternary operation assignment? I enjoy using ternary for statements and operations because of it's simplicity, so any help would be appreciated.

ANSWER Thanks to @Barmar, who suggested the use of the eval() function, I was able to wrap it around the ternary operation.

$.each(videos, function(i, video) {
    eval ("$(home_page_feed)" +
        ((video.special_interest) ? 
            ".prepend(video.thumbnail)" :
            ".append(video.censornail)"
        )
    );
});

Solution

  • You can put the ternary in the argument to .append()

    $.each(videos, function(i, video) {
        $(home_page_feed).append(video.special_interests ? video.thumbnail : video.censornail);
    });
    

    Or you can put it in the index:

    $.each(videos, function(i, video) {
        $(home_page_feed).append(video[video.special_interests ? "thumbnail" : "censornail"]);
    });
    

    Note the quotes in the last version.

    You could do your code using eval()

    $.each(videos, function(i, video) {
        var chain = video.special_interest ? 
            ".prepend(video.thumbnail)" :
            ".prepend(video.censornail)";
        eval ("$(home_page_feed)" + chain);
    });