Home > Software engineering >  How would I have this sum print out it works
How would I have this sum print out it works

Time:02-27

function testSum(){
    var expected = 7
    var actual = sum(5, 2)

    if (actual != expected) {
        console.log("It's broken..")
    } else {
        console.log("It works!")
    }
}

I don't know how to work this out, please help

CodePudding user response:

In a python programming language, you can use sum as the sum of array elements such as sum(iterable, start). However, in javascript sum is "undefined" unless you define that function. Just sum as 2 7.

CodePudding user response:

Your code gives the expected output after calling the function. Though you haven't provided details on your sum function. So I can't speak on whether your sum function is returning the correct result.

I gave an example implementation of sum that checks whether a and b are numeric.

function sum(a, b) {
  if (!isNaN(a) && !isNaN(b)) 
  {
    return a   b;
  }
}

function testSum(){
  var expected = 7
  var actual = sum(5,2)

  if (actual != expected) {
      console.log("It's broken..")
  } else {
      console.log("It works!")
  }
}

testSum();

CodePudding user response:

You could define a sum function that takes two numbers and returns the sum i.e.,

the total amount resulting from the addition of two or more numbers, amounts, or items.
"the sum of two prime numbers"

function sum(a, b) {
    return a   b
}

function testSum() {
    var expected = 7
    var actual = sum(5, 2)
    if (actual != expected) {
        console.log("It's broken..")
    } else {
        console.log("It works!")
    }
}

testSum()

  • Related