title: Codewars Challenge - JavaScript - Find the first non-consecutive number in Array
body: <p><a href="https://www.codewars.com/kata/58f8a3a27a5c28d92e000144/train/javascript" rel="nofollow noreferrer">Link to Codewars challenge</a></p>
  
  <p>This is very basic, but for some reason, I can't figure out why I'm not able to return <code>null</code> when there are <strong>not</strong> any non-consecutive numbers in an array. My code works fine when the array is not totally consecutive: </p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function firstNonConsecutive(arr) {
    for (let i = 0; i &lt; arr.length; i++) {
      if (arr[i + 1] - arr[i] !== 1) {
        return arr[i + 1];
      }
    }
    return null;
  }
  
  
  console.log(firstNonConsecutive([ 0, 1, 2, 3, 4, 6, 7, 8, 9 ]));</code></pre>
  </div>
  </div>
  </p>
  
  <p>But if the array <em>is</em> consecutive, i.e. like this:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function firstNonConsecutive(arr) {
    for (let i = 0; i &lt; arr.length; i++) {
      if (arr[i + 1] - arr[i] !== 1) {
        return arr[i + 1];
      }
    }
    return null;
  }
  
  console.log(firstNonConsecutive([ 6, 7, 8, 9, 10, 11, 12 ]));</code></pre>
  </div>
  </div>
  </p>
  
  <p>You can see that it returns <code>undefined</code> instead of <code>null</code>. Why isn't it returning null? The return is outside of the for-loop. </p>
  
  <p>I tried to create an initial check to see if the array is not consecutive, like this:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function firstNonConsecutive(arr) {
    let newArr = [];
    for (let j = arr[0]; j &lt; arr[arr.length - 1]; j++) {
      newArr.push(j);
    }
    //check if arr does not contain consecutive characters
    if (String(arr) !== String(newArr)) {
      for (let i = 0; i &lt; arr.length; i++) {
        if (arr[i + 1] - arr[i] !== 1) {
          return arr[i + 1];
        }
      }
    }
    else {
      return null;
    }
  }
  console.log(firstNonConsecutive([ 0, 1, 2, 3, 4, 6, 7, 8, 9 ]));</code></pre>
  </div>
  </div>
  </p>
  
  <p>But it did not make a difference. Any ideas?</p>