1

return stops a function and returns a value. For example this simple function returns 2 words.

function returnValue(name) {
    return "Hello " + name;
}

document.getElementById("box-1").innerHTML = returnValue("Freddy");

However I can accomplish the same thing with a variable. For example this function creates the same output without return.

var testVar;

function returnValue(name) {
    testVar = "Hello " + name;
}

returnValue("Freddy");  
document.getElementById("box-1").innerHTML = testVar;

As a noob, at least on the surface I don't see a significant benefit to return compared to a variable. Am I missing something that is uniquely good about return? Or alternately do most people simply use variables?

2
  • The second function of yours is not return anything. It just assign the value to the global variable. Commented Jul 8, 2017 at 2:12
  • Most of the code I saw is using your first solution (Use return) Commented Jul 8, 2017 at 2:15

3 Answers 3

1

Return statements tell the processor to return to the code that called the function. It also has the capability to report values. Using a reporter variable does not cause the function to cease.

Look below:

function returnValue(name) {
    if (name == "Tim") return "Bye " + name;
    return "Hello " + name;
}

This function stops execution if the name is Tim. With reporter variables"

function returnValue(name) {
        if (name == "Tim") testVar = "Bye " + name;
        testVar = "Hello " + name;
}

Even if the name is Tim, execution continues and the value is incorrectly reported as Tim. The variable also takes up unneccesary memory.

Sign up to request clarification or add additional context in comments.

2 Comments

Very interesting! So in a nutshell the power of return rests in its ability to terminate a function.
Precisely. In C/C++, the return type can also be controlled
1

The return statement can be used to accomplish many different things, here are a few examples...

Example 1:
In this example we have a very large loop with a condition, if we don't use the return statement in our condition it will continue to loop through every other number ultimately slowing down our code.

function aLargeLoop() {
  for (i = 0; i < 600; i++) {
    alert(i)
    if (i == 10) {
      return i;
    }
  }
}

aLargeLoop()

Example 2:

Instead of doing this which wastes an unnecessary amount of time to type...

var testVar;

function returnValue(name) {
  testVar = "Hello " + name;
}
returnValue("Freddy")
alert(testVar)

We can accomplish the same thing by just doing...

function sayhello(name) {
  return "Hello " + name;
}

var greeting = sayhello("John")
alert(greeting)

Example 3:

If we try to prototype a method like so...

var x;
Array.prototype.methodExample = function() {
    x = this;
  }
  [1, 2, 3, 4].methodExample()
alert(x)

it isn't going to work, we need to return it like so...

Array.prototype.methodExample = function() {
    return this;
}

alert([1,2,3,4].methodExample())

I hope this helps anyone else with a similar query.

Comments

1

Your variable is a global variable so it can be accessed or set from anywhere in your code. In a web browser there are many global variables which are objects with functions. These are good mainly for storing data.

A function on the other hand can be used to execute a block of code or return an object.

For example, you can define a function to extract text from a string. This function will parse the R(red)G(green)B(blue) parts from a string representing a color in either Hexadecimal, RGB or RGBA format.

function getRGB(color) {
                var Rhex, Ghex, Bhex;
                var R8bit = null;
                var G8bit = null;
                var B8bit = null;
                var IsHex = false;
                if (color.match(/rgba?\((\d{1,3}),\s(\d{1,3}),\s(\d{1,3})/)) {
                    Rhex = RegExp.$1;
                    Ghex = RegExp.$2;
                    Bhex = RegExp.$3;
                }
                else if (color.match(/^\s*#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})\s*$/i)) {
                    Rhex = RegExp.$1;
                    Ghex = RegExp.$2;
                    Bhex = RegExp.$3;
                    IsHex = true;
                }
                else if (color.match(/^\s*#?([0-9a-f])([0-9a-f])([0-9a-f])\s*$/i)) {
                    Rhex = RegExp.$1 + RegExp.$1;
                    Ghex = RegExp.$2 + RegExp.$2;
                    Bhex = RegExp.$3 + RegExp.$3;
                    IsHex = true;
                }
                else {
                    return (NaN);
                }
                if (IsHex) {
                    R8bit = parseInt(Rhex, 16);
                    G8bit = parseInt(Ghex, 16);
                    B8bit = parseInt(Bhex, 16);
                } else {
                    R8bit = parseInt(Rhex);
                    G8bit = parseInt(Ghex);
                    B8bit = parseInt(Bhex);
                }
                return [R8bit, G8bit, B8bit];
            }

Now I can use that function from another function, for example to darken or lighten the color by increasing or decreasing the RGB components of the color:

function darken(color)  {
    var rgb = getRGB(Color);
    return [Math.Max(rgb[0]-1,0), Math.Max(rgb[1]-1,0), Math.Max(rgb[2]-1,0)];
}

Or to lighten a color:

function lighten(color)  {
    var rgb = getRGB(Color);
    return [Math.Min(rgb[0]+1,255), Math.Min(rgb[1]+1,255), Math.Min(rgb[2]+255,0)];
}

I can also declare variables and functions inside of a function:

function myColorHelper(e)
{
    var el = $(e);
    var myColor= function() { return el.css("color"); };
    var myrgb = function() { return getRGB(mycolor);};
    var makeDarker = function() {
       var darker = darken(myrgb());
       el.css("color", "rgb(" + darker[0] + ", " + darker[1] + ", " + darker[2]);
      };
    var makeLighter = function() {
       var lighter = lighten(myrgb());
       el.css("color", "rgb(" + lighten[0] + ", " + lighten[1] + ", " + lighten[2]);
      };

}

Plugins and frameworks are full of functions which allow us to use functionality in our code. For example, I could use jQuery with these functions to darken or lighten the color of an element on a webpage.

var helper = myColorHelper($('#myElement'));
helper.makeLighter();
helper.makeDarker();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.