Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use 'return' in javascript

I'm learning about javascript using various books and I'm noticing that I can't find an adequate explanation of when, exactly, you use return. I understand that you use it when you want to return a value from a function, but then there's examples such as this from Javascript: The Good Parts:

var quo = function(status) {
    return {
        get_status: function() {
            return status;
        }
    };
};

var myQuo = quo("amazed");

document.writeln(myQuo.get_status());

Why does status have to be returned when it is already available to the quo function as an argument? In other words, why does simply

return {
    get_status: status;
}

not work?

Another example on the page immediately following:

var add_the_handlers = function(nodes) {
    var helper = function(i) {
        return function(e) {
            alert(i);
        };
    };
    var i;
    for (i = 0; i<nodes.length; i+=1) {
        nodes[i].onclick = helper(i);
    }
};

Why are we returning alert(i) within a function instead of simply putting alert(i)?

like image 584
tom c Avatar asked Sep 21 '26 11:09

tom c


1 Answers

return {
    get_status: status
}

would not define a getter, that is a function returning the underlying value. It would only define a property.

You would use it as

var status = quo.get_status;

And any user could change the status with

quo.get_status = 'new status directly changed';

One of the reason to use

return {
    get_status: function() {
        return status;
    }
};

is that it makes status private : the users of the quo object can't change the internal status property of the quo object, they can only read it with

var status = quo.get_status();
like image 119
Denys Séguret Avatar answered Sep 24 '26 01:09

Denys Séguret