0

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?

4
  • var foo = ('<?php echo $foo; ?>') ? '<?php echo $foo; ?>' : null; didn't work? Commented Mar 9, 2017 at 11:04
  • You JS should work, just output a "falsy" value from PHP when $foo is null. Commented Mar 9, 2017 at 11:04
  • @smarber the issue seems to be that the PHP code doesn't output anything, so the JS will still error. Commented Mar 9, 2017 at 11:05
  • Please notice the quotes around <?php ... ?> Commented Mar 9, 2017 at 11:14

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You need to return a falsy value from php. Your code was almost correct. It was only missing the quotes around it.

var foo = '<?php echo $foo; ?>' || null;
console.log('foo', foo);   // null

This is because when $foo is empty, it will be var foo = '' || null; and since '' is falsy in Javascript, it will return null.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.