Multiple task using functions

Can a function have multiple task, for instance:

let number = 123;

function f1(param) {
  return (typeof param);
  return param + 4;
}

console.log(f1(number));

Here the console will only return the first task but not both.
If I delete the first, then the second will be shown.

Thanks.

You can only return one thing. You can place a control structure in the function to return based on a condition.

const num= 3;
let isGreater  = isGreaterThanFive(num);
console.log(isGreater);

function isGreaterThanFive(num) {
    if (num > 5) {
         return true;
    }

    return false;
}

In your example you can return both things in a string or array…etc

let number = 123;

function f1(param) {
  return `typeof: ${typeof param}, value: ${param + 4}`;
}

console.log(f1(number));
1 Like

use conditional statements to change the flow of your program.

use loops to repeat the task.

return will exit you from loop, function or even the script.

so, wrapping your return statement in a conditional statement can allow you to check for different values.

For testing purpose use console.log(variable_or_expression)
The way I see your program, you want to know the type of the param and then return the param by adding 4.
So, probably console.log(typeof param) is what you need.

1 Like

Because there is 2 return in 1 block of code,
that cause just one of the line code can return result

remember one function return one result,
in this case you want to return the type of param and you want to add by 4

here is my solution

let number = 123;

function f1(param) {
 //make the result an object
  return {
          type: typeof param,
          result: param + 4,
     }
}

//destructuring function
const {type, result} = f1(number)

console.log(`type : ${type} | result : ${result}`)
1 Like

In JavaScript, a function can only return a single value. However, there are multiple ways to return multiple values from a function.

You can return an array that contains multiple values. The function can construct the array and return it, and the caller can access the individual values by indexing the array.

Instead of returning an array, you can return an object that contains multiple properties. Each property can represent a different value, and the caller can access the values by referencing the corresponding property.