I'm checking the number of digits in a string using the match
and length
properties. Here is the codepen with my function http://codepen.io/PiotrBerebecki/pen/redMLE
Initially when returning numberOfDigits.length
I was getting an error message (Cannot read property 'length' of null
). I've solved this issue by changing the line to (numberOfDigits && numberOfDigits.length)
.
This works but I would like to get a better understanding why the new statement can be executed now. Does the interpreter execute the `numberOfDigits.length now?
Also, why are we getting the same errors when the operands are reversed (numberOfDigits.length && numberOfDigits)
?
Here is the full JavaScript code:
function checkLength(str) {
let numberOfDigits = str.match(/\d/g);
return (numberOfDigits && numberOfDigits.length);
}
console.log( checkLength('T3xt w1th sOme numb3rs') );
console.log( checkLength('Text with some numbers') );
UPDATE 1: The answers below explained that:
- The order of the operands in the
&&
expression counts. - JavaScript optimises the
&&
operator and if the first operand evaluates to null then JavaScript does not check the second one as the expression cannot evaluate to nothing else thannull
/false
.