I check the number of digits in a string using the match and length properties. Here is the code with my function http://codepen.io/PiotrBerebecki/pen/redMLE
Initially, when I returned numberOfDigits.length I received an error message ( Cannot read property 'length' of null ). I solved this problem by changing the line to (numberOfDigits && numberOfDigits.length) . This works, but I would like to better understand why a new statement can be executed at present. Now the interpreter executes `numberOfDigits.length?
In addition, why do we get the same errors when the operands are reversed (numberOfDigits.length && numberOfDigits) ?
Here is the complete 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 explain that:
- The order of the operands in the
&& expression is counted. - JavaScript optimizes the
&& operator, and if the first operand evaluates to null, then JavaScript does not check the second, because the expression cannot evaluate to anything other than null / false .
javascript null logic logical-operators string-length
Piotr berebecki
source share