Search code examples
javascriptphpoperator-keywordternary

ternary operator in javascript when variable is empty


I have used the ternary operator in php $foo = get_field('foo') ?: null; but I'm looking forn an equivalent in javascript. So far I've tried the var foo = <?php echo $foo; ?> || null;. But since <?php echo $foo; ?> in this case is null/empty the console is giving me the error Uncaught SyntaxError: Unexpected token || since the variable is var foo = || null;.

Is there another way of using ternary operators in javascript?


Solution

  • Your problem has nothing to do with ternary operator, but with PHP output to javascript. The safest way is:

    var foo = <?php echo json_encode($foo); ?> || null ;
    

    The json_encode() function makes sure that the variable is echoed in a form that JS understands.