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!
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);