Ad
  • Custom User Avatar

    Note that A[A.length] is undefined too.

  • Default User Avatar

    i is coming up as undefined because you're probably trying to use it outside of your for loop. While normally it's not a problem, by declaring it as let i=0 in your loop construction, you are limiting the scope of i to just that loop.

    For example:

    function findOdd(A) {
      for (let i = 0; i <= A.length; i++){
      
      }
      return i; //i is undefined!
    }
    

    The above code will result in an error with i being undefined.

    This code will not:

    function findOdd(A) {
      for (i = 0; i <= A.length; i++){
      
      }
      return i;
    }
    

    The above will declare i as a global variable, which isn't the best thing to do, but the code will work.

    The best practice is probably to use var like the following:

    function findOdd(A) {
      for (var i = 0; i <= A.length; i++){
      
      }
      return i;
    
    }
    

    The above code will limit the scope of i to just this function. So, if you were to check the value of i outside of this function, it would be undefined.

    let i - is block scoped. That is, i will only exist inside the current block of code, and any blocks within that block.
    var i - is function scoped. i will only exist inside the function in which it is declared.

  • Default User Avatar

    You're writing your solution in the sample test area, or you're writing the solution in the solution area? The 'A' variable doesn't exist until it's passed into your function.

    I guess I'm having trouble understanding what you're doing. When you write a function, you set the variable names for the values that are passed into your function. In javascript, it looks like this:

    function blah(a, b, c){
      return a+b+c;
    }
    

    And then that function can be called from elsewhere. Like this:

    temp = blah(3, 4, 5); //temp will now equal 12
    console.log(temp); //prints 12 to console
    

    In this example, when 3, 4, and 5 are passed to the blah function, the code inside the function will recognize that a == 3, b == 4, and c == 5
    However, if outside your function, you try to call on one of those variables, they won't exist. So if you try this outside of your function code:

    console.log(a);
    

    It won't print 3 to the console, it will print undefined, because a doesn't exist outside of the function code.

    You shouldn't be writing in the sample text box unless you're trying to write your own tests. If you're just trying to come up with a solution, you should just stick to the solution box. The starter code looks like this:

    function findOdd(A) {
      //happy coding!
      return 0;
    }
    

    Outside of the curly brackets of the function, A does not exist.