Question

Hello in php I can do this:

$value = 0;
$test = $value === 0 ? 'it is zero!' : 'It is not zero.';
echo $test;

How can this be done in javascript in 1 line like in php without using the classic if - else if statement?

Was it helpful?

Solution

It still works in javascript

value = 0;
var test = (value === 0 ? 'it is zero!' : 'It is not zero.');
console.log(test);

Output

it is zero!

OTHER TIPS

This should work:

var value = 0;
var test = (value === 0) ? 'It is zero' : 'It is not zero!';
console.log(test);

By the way, it is called a Ternary Operator. Many languages support them.

Almost exactly the same.

var value = 0;
var test = (value === 0) ? 'it is zero!' : 'it is not zero';
console.log(test);

Output:

"it is zero!"
(value == 0)?alert('it is zero!'):alert('It is not zero.');

There is no such major difference except that your $ becomes var.

documentation

I always prefer ternary for inline.I personally find it more readable.

var test =(value===0)?'it is zero!':'It is not zero.';
console.log("test check==="+test)

DEMO : http://jsfiddle.net/jayeshjain24/efLYf/

I can do you 1 better in JS:

var value = 0;
console.log(value === 0 ? 'It is zero!' : 'it is not zero');

Or even shorter:

console.log('it is ' + ((value = 0) === 0 ? '':'not ') + 'zero!');

Bang, one line for your 3 php lines. Note that, this will result either in an Error being thrown (in strict mode), or an implied global variable being created, if value does not exist.
However, if the variable value already exists, all works perfectly fine, and the behaviour is as you'd expect it to be:

var value = 0;
console.log('it is ' + ((value = value || 0) === 0 ? '':'not ') + 'zero!');
//logs it is zero
value = 123;
console.log('it is ' + ((value = value || 0) === 0 ? '':'not ') + 'zero!');
//logs it is not zero

I tested this using an IIFE:

(function(value)
{//logs it is zero
    console.log('it is ' + ((value = value || 0) === 0 ? '':'not ') + 'zero!');
}());
    (function(value)
{//logs it is not zero
    console.log('it is ' + ((value = value || 0) === 0 ? '':'not ') + 'zero!');
}(123));
(function(value)
{//logs it is zero
    console.log('it is ' + ((value = value || 0) === 0 ? '':'not ') + 'zero!');
}(0));

To avoid the code from loggin it is zero when the value is undefined, or falsy:

(function(value)
{//coerce to numbner
    console.log('it is ' + (value === 0 || value === '0' ? '':'not ') + 'zero!');
}());

This will only log it is zero if value is either '0' or 0. It won't for values like false, undefined, null...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top