The difference between logging and returning value is that, if we want to perform certain actions inside the function and we want to get those results and use those results on other functions or assign the result value to a new variable globally, then the returned keyword is what we need. We should define it inside of our functions.
const val1 = 1;
const val2 = 2;
function sumWithReturn(a, b) {
let sum = a + b;
return sum;
}
returning value means we can use the value for performing other actions globally, such as assigning it’s value to a new variable. If we try to log the returned value of the above function, it will display it to the console.
// will log the sum as it returns the value, and value can be access and used globally
console.log(sumWithReturn(val1, val2));
// used the returned value of the sumWithReturn function and assign it to a variable
const sum = sumWithReturn(val1, val2);
// log the value of sum
console.log(sum);
// without returning value, sum variable can be only access inside this code block / locally
// that's why if we tried to log this function, it will return an undefined, but it performs the actions inside
function sumNoReturn(a, b) {
let sum = a + b;
}
// will only returned undefined, but performs actions inside the function.
console.log(sumNoReturn(val1, val2));
// this function will log the value of the sum
// but it doesn't return its values
// if we try to print it, it will return an undefined
function sumWithLog(a, b) {
let sum = a + b;
console.log(sum);
}
// logging the function will returned undefined but it will log the value of sum as we defined a console.log() inside the function.
console.log(sumWithLog(val1, val2));