Home > OS >  JavaScript - I create a function which can sum(start,end) and I want it to return "ERROR"
JavaScript - I create a function which can sum(start,end) and I want it to return "ERROR"

Time:12-19

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.

CodePudding user response:

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.

CodePudding user response:

it is a great rule of thumb to do the validation first before anything else. because Javascript is a high level language, string that has only digit(s) in it like "1" or "100" or "123", Javascript will convert them into number automatically when you do comparison, subtraction, multiplication and division with other number or digit(s) only string. but not addition, because Javascript will concatenate the string instead.

function sumAll(start, end) {
  if(typeof start !== "number" || typeof end !== "number") return "ERROR";
  ...
}
  • Related