Home > Enterprise >  How to return an error from inside an for..of loop in Javascript?
How to return an error from inside an for..of loop in Javascript?

Time:11-06

Im trying to thrown an error from inside an for..of loop that sums array elements. In this case when it is present an object and array as part of the array. Jasmine is passing me all tests except this one. I'll show you my code. Keep in mind i've been learning for two weeks and stuff like .catch and .try I think shouldn't be needed for this exercise. Thanks in advance!

const mixedArr = [6, 12, 'miami', 1, true, 'barca', '200', 'lisboa', 8, 10, 
 { "color": "purple",
  "type": "minivan"}]


function sum(mix) {
  if (mix.length === 0) return 0;
  let mixedSum = 0;
  for (element of mix) {
    if (typeof element === 'string') {
      mixedSum  = element.length;
    } else if (typeof element === 'array' || typeof element === 'object') {  
    throw new error('error')
    } else { mixedSum  = element }
  }
  return mixedSum;
};

console.log(sum(mixedArr))

enter image description here`

I tried to create a new throw that prints a new error. I have seen some throw exercises where they dont use stuff like try and catch, but im obviously missing something here. The goal is to pass the jasmine test.

CodePudding user response:

you can simply use an isNaN() method :

const mixedArr = [6, 12, 'miami', 1, true, 'barca', '200', 'lisboa', 8, 10, 
 { "color": "purple",
  "type": "minivan"}];

function sum(mix)
  {
  let
    len      = mix.length
  , mixedSum = 0
    ;  
  for (element of mix) 
    {
    if (typeof element === 'string')
      {  
      mixedSum  = len;
      }
    else if ( isNaN(element) ) 
      {  
      throw new Error("error unsupported type");
      }       
    else
      {
      mixedSum  = element;
      } 
    }
  return mixedSum;
  }

console.log( sum(mixedArr) )

CodePudding user response:

like Konrad Linkowski said typeof never returns array so you can check for array using Array.isArray and There's also the constructor which you can query directly element.constructor.name == "Array" and you have a syntax error in throw new error so you need to change to throw new Error so your code should be like this

const mixedArr = [
    6,
    12,
    "miami",
    1,
    true,
    "barca",
    "200",
    "lisboa",
    8,
    10,
    { color: "purple", type: "minivan" }
];

function sum(mix) {
    if (mix.length === 0) return 0;
    let mixedSum = 0;
    for (const element of mix) {
        if (typeof element === "string") {
            mixedSum  = element.length;
        } else if (Array.isArray(element) || typeof element === "object") {
            throw new Error("error unsupported type");
        } else {
            mixedSum  = element;
        }
    }
    return mixedSum;
}

console.log(sum(mixedArr));

  • Related