I recently finished a lab and It created few question so I am asking it here, consider following function
function checkLength(arr) {
if (arr.length) {
console.log(`arr has length`);
} else {
console.log(`array is empty`);
}
}
checkLength([])
The question I wan to ask is if I use if(arr.length) it will give true or false based on length. Will it be a valid or which is more preferable?
Yes, if (arr.length) is valid when you only want to check whether an array is empty or not.
If the array is empty, its length will be 0, which is a falsy value and the condition evaluates to false.
If the length is any value other than 0, it’s a truthy value and the condition evaluates to true.
Writing it explicitly as if (arr.length > 0) is also correct (it’s just more verbose).
1 Like
I tend to use what I exactly mean when possible and rarely rely upon truthiness. It helps clarity and maintainability.