Search code examples
javascriptfunctionfizzbuzz

What is the difference between return and console.log()


I get different outputs when I use console.log() in my function vs when I use the return statement.

When I run the function with the return statement I get a one word output which is one of the following: 'fizz' 'buzz' or 'fizzbuzz', but when I run the function using console.log the output is counting to the limit and saying 'fizz' 'buzz' or 'fizzbuzz' whenever it comes across a multiple of 3, 5 or both/ why is this so?

input = fizzBuzz(100)
console.log(input)

function fizzBuzz(limit){
    for (let i = 0; i <= limit; ++i)
    if (i % 3 === 0 && i % 5 === 0) 
    console.log('fizzbuzz')
    else if (i % 3 === 0)
    console.log('fizz')
    else if (i % 5 === 0)
    console.log('buzz')
    else console.log(i)
}


input = fizzBuzz(100)
console.log(input)

function fizzBuzz(limit){
    for (let i = 0; i <= limit; ++i) {
        if (i % 3 === 0 && i % 5 === 0)
            return 'fizzbuzz'
        else if (i % 3 === 0)
            return 'fizz'
        else if (i % 5 === 0)
            return 'buzz'
        else return i
    }
}

I think it is because the return statement stops the function from executing anything further but I am not sure, still new and self teaching!


Solution

  • return evaluates its argument (if supplied) and ends the execution of the containing function immediately.

    console.log evaluates its argument and prints it, continuing the execution of the function it's called from.

    So in your example with return, the fact that you're in a for-loop that goes limit times doesn't matter, because you'll only go through it once and return from fizzBuzz.

    Putting it all together with another example:

    function print_dog() {
      console.log('dog');
      return;
      console.log('cat');
    }
    

    If you then call print_dog(), you'll see the output dog, but you won't see the output cat, because return ends execution of print_dog before it can get to console.log('cat');