DEV Community

Discussion on: Write beautiful and Elegant Javascript code with short-circuit evaluation.

Collapse
 
frankwisniewski profile image
Frank Wisniewski • Edited

your first sample must be changed to:

let length = 0
if (Array.isArray(arr)) {
    length = arr.length
}
Enter fullscreen mode Exit fullscreen mode

the following code:

let length = (arr || []).length 
Enter fullscreen mode Exit fullscreen mode

is nice to look at, but not to be used in a team. The detailed version is much clearer and even years later it is immediately clear to every reader what is meant.

Collapse
 
fayomihorace profile image
Horace FAYOMI • Edited

indeed, the first version might be more readable as simple code (even if take more lines) is most of the times better code to read.
In my case I use it because it allows me to do the job (getting the length wihout exception) without needing each time to import and call a custom helper function that will do the job instead for reusability purposes.