Javascript - typeless comparison in boolean

In other languages, I have two sets of operators, or and || that are displayed by default. Does Javascript have a set of operators for comparing and returning the original object, and not a boolean?

I want to be able to return whatever value is defined, with one expression like var foo = bar.name or bar.title

+4
source share
5 answers

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

 var bar = { name: "", title: "foo" }; var foo = bar.name || bar.title; alert(foo); // alerts 'title' 

Of course, you must keep in mind the values โ€‹โ€‹of which are evaluated as false .

+6
source
 var foo = (bar.name != undefined) ? bar.name : ((bar.title != undefined) ? bar.title : 'error'); 
+2
source

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

It returns the first defined object.

If none of these are defined, undefined returned.

+2
source

I either completely skipped the question, or just the way you mentioned:

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

if bar.name contains any legal value assigned to it in foo , otherwise bar.title is assigned.

eg:

 var bar = { name: null, title: 'Foobar' }; var foo = bar.name || bar.title console.log( foo ); // 'Foobar' 
+1
source

Javascript behaves exactly the way you want:

 var a = [1, 2], b = [3, 4]; console.log(a || b); //will output [1, 2] a = 0; console.log(a || b); //will outout [3, 4] 

If you want a cast to boolean, you can use the double negative operator:

 console.log(!![1, 2]); //will output true console.log(!!0); //will output false 
+1
source

All Articles