Note that there are some explanatory texts on larger screens.

plurals
  1. PODon't understand (variableName != "") in JavaScript code - Coderbyte Challenge #25: NumberSearch
    primarykey
    data
    text
    <p>I am having difficulty analyzing a line of someone else's JS code for a Coderbyte challenge. We are to search for all numbers in a given string, add them together, and then return the final sum. So "88Hello 3World!" should have an output of 91. "55Hello" should have an output of 55. And "5Hello 5" should output 10. The line of code I'm having difficulty interpreting specifically says:</p> <pre><code>else if (curNum != "") { </code></pre> <p>Please help me understand, what this line, specifically, is doing in the context of the entire function. What does it accomplish? When would curNum === ""? Could you give an example? The line is taken from the following code:</p> <pre><code>function NumberAddition(str) { var result = 0; //creates var result; sets value to 0 var curNum = ""; //creates var curNum; sets value to "" for (var i = 0; i &lt; str.length; i++) { //run thru user-inputted string, for each character... if (str[i] &gt;= "0" &amp;&amp; str[i] &lt;= "9") { //if the current element is b/w 0 and 9... curNum += str[i]; //add the value of that element (as a string) to curNum else if (curNum != "") *** // ***the 1st part of the if statement is relevant if str[i] is a number. What does this else-if branch do and when does it apply???! result += parseInt(curNum); // convert curNum to an integer and add it to result variable curNum = ""; // reset curNum variable to "" / blank } } if (curNum != "") *** // *** again, when does this apply? result += parseInt(curNum); // take whatever's in curNum and convert to an integer and add to result variable } return result; //return result after running thru entire for-loop } </code></pre> <p>If I were to take a stab at it (reading b/w the lines), the line of code will apply when str[i] is not a number, so that the value currently in curNum is converted to a string as soon as str[i] is a character other than a number? Not sure if that makes sense though. But I guess what I'm asking, is what exactly is</p> <pre><code>curNum != "" </code></pre> <p>saying??? And can you please show an example of how it works and when it applies (both uses of it)?...</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload