Explication with the use of Return

Hi guys, I’m learning Javascript and I just want to understand the difference between these to examples:

image
image

On the first picture, no problem, It displays ‘rock’ but on the second picture, I made a modification at the 6th line and added at the 7th line console.log() but It doesn’t display ‘rock’ anymore. Can someone explain It to me please ?

Thank you :smiley:

Hello @system2553229654. return ends a function. That means that any code within the function and after the return does not get executed:

function foo(){
  console.log("foo");//Gets logged on function call
  return "bar";//this is what the function returns
  console.log("This won't be printed");//This does not get printed-it is after the return
} 

Because you have a return in the second example, you need to do something with that return. A return will return the value provided to it, which means you can store the result of a function in a variable, and do other things like that with it:

function foo(){
  return "foo";
}
let var1 = foo();
console.log(var1);//will print "foo"

So, in order for you to view ‘rock’ when calling the second function, you would have to console.log it:

console.log(getUserChoice("rock");//this will now print "rock", because you are utilising the return of the function.

When calling a function, if you print a function with no return, the result is undefined (because you are printing nothing-no return, no value to print), conversely, if you only call a function, but not print it, you will get nothing:

function foo(){
return "foo";
}
foo();//This won't print anything because all you are doing is getting the value the function is returning, but not doing anything with it.
console.log(foo());//This prints "foo"
function bar(){
  console.log("bar");
}
console.log(bar());//This will print undefined as there is no value being returned from the function.
bar();//This will print 'bar', as that is what the function does.

I hope this helps!

1 Like

It helps A LOT. Thank you so much ! Last question now I got this:

image

What can I write so that It doesn’t display ‘undefined’ when the value is not ‘rock’ or ‘paper’ or ‘scissors’, I just want It to display ‘Your choice is not valid’. :laughing:

1 Like

You can use return, if you want to keep with using returns in your code:

function foo(){
  return "foo";//This will return 'foo' when called.
}

(see the blurred box if you are stuck):

}else{
  return "Your choice is not valid";
}

Happy coding!

1 Like

It works perfectly ! Thank you so much for helping me !!! :raised_hands: :grin:

1 Like