javascriptarrayslistalgorithm

null length on javascritp array


I've to read the elements of an array and sum up both positive and negative values inside it and the array can be null or empty.

I've wrote the following code and it work fine

function countPositivesSumNegatives(input) {
  var arrOutput = []; //declare the final array
  var pos = 0; //declare the positive 
  var neg = 0; //declare the negative
  var check, ss;

  for (var x = 0; x < input.length; x++){
    if(input[x]>0){ pos++; }
    else{ neg = neg + input[x] ; }
    arrOutput = [pos, neg]
  }
  
  return arrOutput;
}

but it returns me the following error:

TypeError: Cannot read property 'length' of null
    at countPositivesSumNegatives (test.js:8:29)
    at Context.<anonymous> (test.js:39:18)
    at processImmediate (internal/timers.js:461:21)

and because of this error i can't pass the test.

How can i solve it, and why it gives me this error?


Solution

  • So if we call your function with the input equal to null / undefined:

    function countPositivesSumNegatives(input) { // input = null
      var arrOutput = []; // OK
      var pos = 0; //OK 
      var neg = 0; //OK
      var check, ss; // OK
    
      for (var x = 0; x < input.length; x++){ // error is here
      ...
    

    In JS, null is defined as: "a primitive value that represents the intentional absence of any object value"

    So when you try to access a member of null, JS is going to throw an error because null has no members.

    You have a variable for check, but you should write code for that check to see if the input is equal to any of the illegal values you mentioned.

    A simple, brute force, solution would be to just check if the input is equal to any illegal values. E.g.

    if (input === null || input === undefined || input === []) return []

    Before the for loop.