简体   繁体   中英

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; var foo = <?php echo $foo; ?> || null; . But since <?php echo $foo; ?> <?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; var foo = || null; .

Is there another way of using ternary operators in javascript?

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.

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; var foo = '' || null; and since '' is falsy in Javascript, it will return null.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM