i am learning javascript with a udemy tutorial and also youtube.. and it went pretty well with template literals, also ternary operator, and other operator such as logical and arithmetic, but when i encountered functions, it's a whole new level of frustrations.
before the question just to make sure i understand, the return keyword is used in order to be able to reuse the code inside the function later in my program, but in this specific example, it works even without the return keyword.. so why do i need it??
code:
function fruitProcessor(apples, oranges) {
console.log(apples, oranges);
const juice = `juice with ${apples} apples and ${oranges} oranges`;
// return juice; working even without it.
}
fruitProcessor(5, 2)
can someone correct me if i am wrong about the basic idea of return keyword? and also explain to me regarding my question? thanks!
CodePudding user response:
If you want to just run the code inside the function, you don't have to return anything. However, if you want to use a result of a calculation, then you can return
whatever you want from any function you define.
For example, let's use the following function:
function sum(a, b) {
const ans = a b;
console.log(ans);
return ans;
}
You can see that it does 3 steps:
- Calculate the sum of its arguments.
- Log the sum (using `console.log).
- Return the sum.
Then, if you just call the function you'll do all these steps - but will ignore the returned value:
sum(1, 2); // Will log '3'
However, you're also able to use the returned value:
const foo = sum(1, 2); // Will log '3'
console.log('The sum is ' foo); // Will log 'The sum is 3'
CodePudding user response:
From the MDN documentation:
The return statement ends function execution and specifies a value to be returned to the function caller.
In that regard, a function not always is used just to print an statement in a console.
Taking your example, you can remove the console.log statement and work with the returned value later in your code.
function fruitProcessor(apples, oranges) {
const juice = `juice with ${apples} apples and ${oranges} oranges`;
return juice;
}
console.log(fruitProcessor(5, 2))
or also you can store the function's response in a variable to be used later without calling again the function (and consume more machine time again):
function fruitProcessor(apples, oranges) {
const juice = `juice with ${apples} apples and ${oranges} oranges`;
return juice;
}
let processedFruits = fruitProcessor(5, 2);
let upperCaseFruits = processedFruits.toUpperCase(); //using the variable
console.log(processedFruits);
console.log(upperCaseFruits);