Garry Pettet
Garry Pettet

Reputation: 8290

Operator overloading in Javascript

I'm trying to port this Javascript function (shortened for clarity):

Vertices.scale = function(vertices, scaleX, scaleY, point) {

    point = point || Vertices.centre(vertices);

};

point is a vector, i.e. an object of the form { x: 5, y: 10 }. Vertices.centre(vertices) returns a similar vector object.

As far as I can see, there is no overloading of the '||' operator in the source code. In fact, I don't think you can overload operators in Javascript.

What does this code mean in plain English then?

Upvotes: 2

Views: 159

Answers (1)

madox2
madox2

Reputation: 51841

It is the same as:

Vertices.scale = function(vertices, scaleX, scaleY, point) {
    if (point) {
        point = point;
    } else {
        point = Vertices.centre(vertices);
    }
}

Convention using || (logical OR operator) is shorthand for using default values for function paramters. (but notice that it won't work for boolean parameters).

You can find more about logical operators on MDN

Upvotes: 2

Related Questions