Definition of Return


#1


Exercise 7 and 8.


I'm having trouble understanding the return statement. In the exercise, it defines it as "The return keyword simply gives the programmer back the value that comes out of the function. So the function runs, and when the return keyword is used, the function will immediately stop running and return the value." What I'm assuming is that the return statement just keeps the value within the function until the function is called again later.

Please explain it in layman's terms so I can understand it better. Thank You.


Replace this line with your code.


#2

function only execute when called, so this explanation explains what happens when you call a function

really dull example:

var example = function(){
    return 5;
}
x = example()
console.log(x)

the function returns 5, so when i call the function, i store what the function returns in a variable named x, so x will now be 5, which i prove by logging x on the next line, the output should show 5


#3

That's essentially what it does, yes.


Take this function for example

function sayHello() {
  return 'Hello World';
}

If you run it as is, it will just return "undefined", because you're not printing anything.
You're basically saving Hello World within the function.

This is a method that can be called upon whenever you might need it.


Now, if you called the function

function sayHello() {
  return 'Hello World';
}
sayHello();

The output will then be "Hello World", because you called it.


#4

in the exercise this might happen, because the exercise is a bit more beginners friendly, see what happens you run your code outside the exercise (here for example)

nothing will show, and nothing will show in browser console. Because the function returns, you need to call console.log() on sayHello function call to log the returned value (or like i did, first save the return value in variable and then log it)


#5

Strange. This example is based on Chrome's console output:


#6

yea, this is defined as console behavior (the exercise also has this). It echoes the last value (whether this is an updated variable, or a function call)

run this code:

function sayHello() {
  return 'Hello World';
}
var example = function(){
    return 5;
}
example();
sayHello();

in one go (in either the chrome console or codecademy exercise) you will only see the value of sayHello.

however, if you where to put this code in a .js file, nothing would show to the console


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.