最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

What does "return" do in Javascript? - Stack Overflow

programmeradmin6浏览0评论

I just taught myself how to code with tutorials from the internet. I'm currently trying to learn Javascript and I don't really undesrtand the purpose of "return". I made a "rock, paper, scissors" game at the end of my lesson, using the return function. The game looks like this:

var userChoice = prompt("Do you choose rock, paper or scissors?");
var puterChoice = Math.random();
if (puterChoice < 0.34) {
    puterChoice = "rock";
} else if(puterChoice <= 0.67) {
    puterChoice = "paper";
} else {
    puterChoice = "scissors";
} console.log("Computer: " + puterChoice);

var pare = function(choice1, choice2){
    if(choice1 === choice2){
        return "The result is a tie!";
    }
    else if(choice1 === "rock"){
        if(choice2 === "scissors"){
            return "rock wins";
        }
        else{
            return "paper wins";
        }
    }
    else if(choice1 === "paper"){
        if(choice2 === "rock"){
            return "paper wins";
        }
        else{
            return "scissors wins";
        }
    }
    else if(choice1 === "scissors"){
        if(choice2 === "paper"){
            return "scissors wins";
        }
        else{
            return "rock wins";
        }
    }
};
pare(userChoice, puterChoice);

What exactly would be the difference if I used console.log("....") instead of "return" here?

I just taught myself how to code with tutorials from the internet. I'm currently trying to learn Javascript and I don't really undesrtand the purpose of "return". I made a "rock, paper, scissors" game at the end of my lesson, using the return function. The game looks like this:

var userChoice = prompt("Do you choose rock, paper or scissors?");
var puterChoice = Math.random();
if (puterChoice < 0.34) {
    puterChoice = "rock";
} else if(puterChoice <= 0.67) {
    puterChoice = "paper";
} else {
    puterChoice = "scissors";
} console.log("Computer: " + puterChoice);

var pare = function(choice1, choice2){
    if(choice1 === choice2){
        return "The result is a tie!";
    }
    else if(choice1 === "rock"){
        if(choice2 === "scissors"){
            return "rock wins";
        }
        else{
            return "paper wins";
        }
    }
    else if(choice1 === "paper"){
        if(choice2 === "rock"){
            return "paper wins";
        }
        else{
            return "scissors wins";
        }
    }
    else if(choice1 === "scissors"){
        if(choice2 === "paper"){
            return "scissors wins";
        }
        else{
            return "rock wins";
        }
    }
};
pare(userChoice, puterChoice);

What exactly would be the difference if I used console.log("....") instead of "return" here?

Share Improve this question edited Jun 10, 2017 at 15:50 Marcos Dimitrio 6,8626 gold badges41 silver badges64 bronze badges asked Jun 10, 2017 at 15:24 RobinbuxRobinbux 591 silver badge7 bronze badges 6
  • Surprisingly enough it "returns" whatever is after it. So if you call the function like var f = test() and test() return a value then f will be that value. – GillesC Commented Jun 10, 2017 at 15:25
  • when you call the function, it will return value based on some conditions console.log( pare(1,1) ); will output the first condition ("The result is a tie!") because the values sent to the function match – Alon Eitan Commented Jun 10, 2017 at 15:26
  • console.log() only prints something in your browsers console. While return give back an expected value from a function which later can be used from another function or class to do more stuff. – Lixus Commented Jun 10, 2017 at 15:26
  • 2 just add another thing : "return" terminates function immediately in javascript . – Minar_Mnr Commented Jun 10, 2017 at 15:30
  • 1 Possible duplicate of Difference between console.log and return in javascript? – Julien Lopez Commented Jun 11, 2017 at 8:41
 |  Show 1 more ment

5 Answers 5

Reset to default 7

According to W3Schools,

The return statement stops the execution of a function and returns a value from that function.

But

console.log writes into the browser console.

In other words, you can't see the output of console.log unless you open 'Developer Tools'

According to MDN (a much more reliable source),

When a return statement is called in a function, the execution of this function is stopped. If specified, a given value is returned to the function caller. If the expression is omitted, undefined is returned instead. The following return statements all break the function execution:

return;
return true;
return false;
return x;
return x + y / 3;

But

console.log() outputs a message to the Web Console.

For example,

function myFunction() {
    return Math.PI;
} 

would return 3.141592653589793 when the function is called.

But using console.log instead, would not show anything, on a webpage (except in developer tools).

In JavaScript, most things are expressions, and every expression has a value. That can be a number (5), a string ("Hello, World!"), an object ({ foo: 'bar' }) or something other, like a regex.

When you use an operator, e.g. choice1 === "rock", that's also an expression, which has a boolean value (true or false). The expression 5 + 3 has a value, too. It is 8.

When you call a function, that's also an expression, which has a value. The prompt function, for example, has the value that the user entered. It's what you get back when you call prompt(...). The value of a function call is refered to as the "return value" of that function.

When you define your own function, you can also give them a return value. And later, when you call the function, this return value is what you get back. Remember functions in the maths class in school? Things like f(x) = x * x? When you "call" f with 5, then 25 is the value of that "function call": f(5) = 5 * 5 = 25.

Now, let's define our own JavaScript function that has a return value:

function add (a, b) {
  return a + b; // make the sum of a and b the return value of "add"
}

var result = add(5, 3); // store the value of the function call
console.log(result); // should log 8

Many built-in JavaScript functions have a return value: Math.min() returns the smallest of the arguments passed to it, document.getElementById() returns the HTML element with the id that you passed to it.

For some functions, it doesn't make any sense to return the result of an action. What should be the result of console.log()? Those functions return the value undefined. When your own functions don't have a return statement, their return value is undefined.

It is very important to note that the execution of a function stops when it hits a return statement. It then immediately returns to the location in the script where the function was called:

function test () {
  console.log('Hello 1');
  return 5; // return to the caller
  console.log('Hello 2'); // will not execute
}

var result = test();
console.log(result); // 5

When you leave out the value after the return ...;, so you just say return;, then the return value will also be undefined. You can use that if you want to stop the execution without a value to return:

function divide (a, b) {
  return a / b;
}

function printQuotient (a, b) {
  if (b === 0) {
    // the divisor is zero, do nothing
    return;
  }
  
  // divisor is not zero, print the result of the division
  console.log(divide(a, b));
}

printQuotient(10, 5); // prints 2
printQuotient(10, 0); // prints nothing

The concept of return is to return something.

for ex you could have var winner = pare(userChoice, puterChoice); That would set the winner as the string returned from the function pare(), and you could use that var later for display. So in all actuality winner could be equal to any of your if/else strings. so for another ex, winner could be read as winner = 'rock wins' (if that was the logical winner)

When a return is encountered in a function. It will return to the point immediately after the code that called the function. If nothing is specified after the return statement, that is all that happens. However if a literal is returned like 2 or 3,etc, a literal is returned. You can also return a Boolean "true/false ", a string, or a variable. Console.log () means what the name implies, it literally displays the value inside the parentheses to the development console. Its primary use is for troubleshooting.

console.log will display or emit the parameter passed to the log method in the console window of your browser and can be used almost anywhere in the code.

Meanwhile when using the return statement, the function will stop executing, and return the specified value.

Read more;

  • What is console.log?

  • Difference between console.log and return in javascript?

  • Why should I use return instead of console.log?

发布评论

评论列表(0)

  1. 暂无评论