Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript – I create a function which can sum(start,end) and I want it to return "ERROR" when input is String but it doesn't work

here is what I’ve tried
`

function sumAll(start, end) {
  let average = Math.abs(start + end) / 2;
  let numberOfTerms = Math.abs(end - start) / 1 + 1;
  if (start >= 0 && end >= 0 ) {
    return Math.abs(average * numberOfTerms);
  } else if(typeof start === 'string' || typeof end === 'string'){
    return "ERROR";
  }else{
    return "ERROR";
  }
}
console.log("sumAll(10, '90') =" + sumAll(10, "90")); // I want this to return "ERROR" because "90" is String
console.log("sumAll(10, '90') =" + sumAll(10, "x"));// this works

`

but when I change input to "x" it works just fine. I think I miss something.
feel free to tell me anything, I’m a beginner. I’d love to learn new thing.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In your current implementation, you are checking whether the type of start or end is equal to the string ‘string’. Instead, you should be using the typeof operator to check the type of the variables.

Here is how you can modify your function to check for string input and return "ERROR" in that case:

    function sumAll(start, end) {
  if (typeof start === 'string' || typeof end === 'string') {
    return "ERROR";
  }
  let average = Math.abs(start + end) / 2;
  let numberOfTerms = Math.abs(end - start) / 1 + 1;
  if (start >= 0 && end >= 0 ) {
    return Math.abs(average * numberOfTerms);
  } else {
    return "ERROR";
  }
}

console.log("sumAll(10, '90') =" + sumAll(10, "90")); // "ERROR"
console.log("sumAll(10, 'x') =" + sumAll(10, "x")); // "ERROR"

With this modification, the function will return "ERROR" when either start or end is a string.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading