DEV Community

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

Collapse
 
pengeszikra profile image
Peter Vivo
const length = Array.isArray(arr) ? arr.length : 0;

// or 

const length = arr?.length ?? 0;
Enter fullscreen mode Exit fullscreen mode

Maybe the first is sort enough and give back result 0 for string too.

Collapse
 
fayomihorace profile image
Horace FAYOMI

Indeed ternary expression are another way to write short and beautiful code.
I'll cover it in another article.

Collapse
 
boredcity profile image
boredcity
const length = arr?.length ?? 0;
Enter fullscreen mode Exit fullscreen mode

is the way to go. why create an empty array when you just want to get 0?

Collapse
 
fayomihorace profile image
Horace FAYOMI

Indeed, this is better, thanks.