Returning Values From Functions

Using Functions

Returning Values From Functions

🙋 Need help? Ask an expert now!

As mentioned previously, every function in JavaScript returns a value. If the function doesn't explicitly return a value, undefined is returned. The return type can be of any data type, including Number, String, Object, Function, etc. Defining a function that returns a value is quite simple. As long as the return keyword exists in your function, it returns a value. The return statement immediately terminates the function's execution and returns the specified expression to the caller. It can be used several times in a function body to return a different value depending on the situation.

The sample code above has two functions, multiply() and isEven. The first functions takes in two numbers and returns the product of the two numbers. The second function takes in a number and returns true or false depending on whether or not the number is even. The second method has two return statements, and since the return statement exits the function when it is called, it will never return both true and false.

Edit Me on GitHub!

Application Question

Consider the following code segment:

function divide(number) {
  if (number % 7 == 0){
    return "divisible by 7";
  } else if (number % 5 == 0){
    return "divisible by 5";
  } else if (number % 5 == 0 && number % 7 == 0){
    return "divisible by 5 and 7";
  } else {
    return "not divisible by 5 or 7";
  }
}

Which of the following function call returns the output "divisible by 5 and 7"?