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