What is the difference of using the return keyword rather than using just a console.log function and just passing the parameters?

Viewed 60

I have watched a tutorial wherein he made a square() function that accepts any number as a parameter. The function he made looks like this:

function square(number) {
   return number * number;
};

let number = square(2);
console.log(number);

I tried doing the same function by just using the console.log within the function itself, like this:

function square(number) {
   console.log(number * number)
};

square(2);

Both code worked but I do not know the difference between the two. Can you please explain to me what is the catch of using either ways? Or better, please provide any reading materials I can use regarding my inquiry.

3 Answers

The return statement allows you to assign the output to a variable. For example:

function square(number) {
   return number * number;
};

let a = square(3); // assigns  9 to variable a.
let b = square(4); // assigns 16 to variable b.
let c = a + b;
console.log(c); // prints 25.

By using the return keyword, you are able to send data back to the original caller of the function. For example, let's consider your two code blocks:

function square(number) {
   return number * number;
};

const sq = square(5);
console.log(sq); // 25

Now, consider if we call console.log inside the function itself:

function square(number) {
   console.log(number * number)
};

const sq = square(5);
console.log(sq); // undefined

What a return statement allows us to make the function act like a call and response: Ask a question, get an answer. This can be useful when you want more complicated code. For example, here's an example adding to squared numbers.


function square(number) {
   return number * number;
};

const a = square(5);
const b = square(10);

console.log(a + b);

This sort of operation wouldn't be possible with the previous function

The difference between the two functions goes as this:

The first function follows the simple steps of:

  1. call the function with the value 2
  2. multiply 2 * 2
  3. send the value back to line the function is called at, in this case it would be 4
  4. save that value (4) returned from the function to a variable known as "number"
  5. display the value of number (4) to the console
  6. end function

the second function does something more along the lines of:

  1. call the function with the value 2
  2. display the value of (2 * 2)
  3. end function

The first function allows us to use number outside of the function. So we can then maybe pass number back into the function to get a value of 8, while in the second function the value of 4 never leaves the scope of the function.

Related