Search code examples
javascriptreturnvar

How do I assign a return statement to a variable in Javascript?


var robotLeaves = "The robot has left to get milk!"
var byeRobot = return robotLeaves;

I'm trying to display what's assigned to the robotLeaves variable by using a return statement. Additionally, I'm trying to assign that return statement to a variable so I can reuse it.

Which websites || resources should I check out in order to find the solution for how to accomplish this?

edit: Here's the full code I'm experimenting with:

function getMilk() {
  var shop = 10;
  var robotLeaves = "The robot has left to get milk!"
  var robotReturns = "The robot has come back with 1 bottle of milk!"
  var byeRobot = return robotLeaves;

  byeRobot;
  if(byeRobot) {
    --shop;
    return robotReturns;
    return shop;
  };
}
getMilk();

2nd edit: It turns out I was using the return statement incorrectly! Thank you to all who posted!


Solution

  • No offense but what you're trying to do is pretty weird. return isn't like a function or a variable that gives you a value, it only takes values. You put it in a function, and whatever you return is what you get when you use the function later on. It's always the last thing a function does, when it returns, it stops executing. So return doesn't display anything, but you can pass whatever value you return to a function that DOES.

    function getRobotState() {
      return "The robot has left to get milk!";
    }
    
    var robotLeaves = getRobotState();//Run the function, retrieve whatever it returns, put it in a variable so you can reuse it.
    //Display value
    console.log(robotLeaves)
    //You can use robotLeaves as many times as you want from here downwards.
    postOnTwitter("Where is the robot? " + robotLeaves)