Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Compare without typecasting to boolean

Tags:

javascript

In other languages I have two sets of operators, or and ||, which typecast differently. Does Javascript have a set of operators to compare and return the original object, rather than a boolean value?

I want to be able to return whichever value is defined, with a single statement like var foo = bar.name or bar.title

like image 430
wersimmon Avatar asked Dec 16 '22 10:12

wersimmon


2 Answers

There is only one set of boolean operators (||, &&) and they already do that.

var bar = {
    name: "",
    title: "foo"
};

var foo = bar.name || bar.title;

alert(foo); // alerts 'title'

Of course you have to keep in mind which values evaluate to false.

like image 114
Felix Kling Avatar answered Jan 02 '23 08:01

Felix Kling


var foo = (bar.name != undefined) ? bar.name : 
          ((bar.title != undefined) ? bar.title : 'error');
like image 32
Naftali Avatar answered Jan 02 '23 10:01

Naftali