Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending the logical OR || syntax for the empty array

Tags:

javascript

Let f and g be two function. Then f() || g() first evaluates f. If the return value of f is falsy it then evaluates g, and returns g's return value.

I love the neat and concise syntax, but it doesn't include the case where f returns the empty array [], which I want to consider "falsy".

Is there clean way of having this syntax for [] instead of the traditional falsy values?

like image 254
Randomblue Avatar asked Sep 07 '11 01:09

Randomblue


People also ask

What is the length of an empty array?

If the length of the object is 0, then the array is considered to be empty and the function will return TRUE.

What does '!' Mean in JavaScript?

The ! symbol is used to indicate whether the expression defined is false or not. For example, !( 5==4) would return true , since 5 is not equal to 4. The equivalent in English would be not .

What does|| means in JavaScript?

The logical OR ( || ) operator (logical disjunction) for a set of operands is true if and only if one or more of its operands is true. It is typically used with boolean (logical) values.

Can array size be empty?

The length property sets or returns the number of elements in an array. By knowing the number of elements in the array, you can tell if it is empty or not. An empty array will have 0 elements inside of it. Let's run through some examples.


1 Answers

You could write a function that converts the empty array into a real falsy value, maybe?

function e(a) { return a instanceof Array ? (a.length ? a : false) : a; }

var result = e(f()) || g();
like image 55
Casey Chu Avatar answered Sep 29 '22 09:09

Casey Chu