SkyeBoniwell
SkyeBoniwell

Reputation: 7092

null value not be evaluated in JavaScript ternary operation

I have a javascript game with this function that displays data when the user hovers over a certain element.

This is what it looks like:

gameRendering: function (game, e) {

    var playerCharacterTitle = game.playerCharacterTitle;

    
    $(user).hover({
        content: '<b>Game Characters</b>'
            + (playerCharacterTitle) !== null ? '<b>PC Name:</b> ' + playerCharacterTitle : ''
    });
    

When variable named, playerCharacterTitle, is NOT null, I want it to display this: "PC Name: {the_name}" and when the name is null, I want it to display nothing.

Like this:

PC Name: Gorak

PC Name: LeMara

But for some reason, it's still displaying "PC Name:" and then a 'null'... like this:

PC Name: Gorak

PC Name: null

PC Name: LeMara

PC Name: null

I am getting no errors, just results that I don't like.

What could I be doing wrong?

Thanks!

Upvotes: 0

Views: 16

Answers (1)

Arthur Rubens
Arthur Rubens

Reputation: 4706

You have forgotten to put the brackets (a so called operator precedence rules):

gameRendering: function (game, e) {

    var playerCharacterTitle = game.playerCharacterTitle;

    
    $(user).hover({
        content: '<b>Game Characters</b>'
            + (playerCharacterTitle !== null ? '<b>PC Name:</b> ' + playerCharacterTitle : '')
    });

function gameRendering(game, e) {

    var playerCharacterTitle = game.playerCharacterTitle;

    
    //$(user).hover({
        var content = '<b>Game Characters</b>'
            + (playerCharacterTitle !== null ? '<b>PC Name:</b> ' + playerCharacterTitle : '')
    //});
    console.log(content)
}

gameRendering({playerCharacterTitle: null}, 'a');
gameRendering({playerCharacterTitle: "SomeName"}, 'a');

Upvotes: 1

Related Questions