Steve
Steve

Reputation: 514

Assignment syntax

I came across the following code on http://www.somethinghitme.com/2013/11/11/simple-2d-terrain-with-midpoint-displacement/.

function terrain(width, height, displace, roughness, seed) {
    var points = [],
        // Gives us a power of 2 based on our width
        power = Math.pow(2, Math.ceil(Math.log(width) / (Math.log(2)))),
        seed = seed || {
            s: height / 2 + (Math.random() * displace * 2) - displace,
            e: height / 2 + (Math.random() * displace * 2) - displace
        };

    // ...
}

I am unfamiliar with this syntax. What exactly does it achieve? What will the points variable contain after this assignment?

Upvotes: -1

Views: 68

Answers (3)

user2864740
user2864740

Reputation: 61875

The following production is a Variable Statement, which allows multiple declarations to appear, separated by commas.

var points = [],
   // Gives us a power of 2 based on our width
   power = Math.pow(2, Math.ceil(Math.log(width) / (Math.log(2)))),
   seed = seed || {
        s: height / 2 + (Math.random() * displace * 2) - displace,
        e: height / 2 + (Math.random() * displace * 2) - displace
   };

It is treated the same as using individual variable statements, and the choice of which form to use is a stylistic preference. (I choose the latter, jslint suggests the former.)

var points = [];
var power = Math.pow(2, Math.ceil(Math.log(width) / (Math.log(2))));
var seed = seed || {
  s: height / 2 + (Math.random() * displace * 2) - displace,
  e: height / 2 + (Math.random() * displace * 2) - displace
};

The one interesting thing to note is var seed = seed || .., where seed is already a parameter. This is because var does not "define" a variable, as in a language like C, but rather the declaration applies a scope-wide annotation. As such there is only one seed variable for the entire scope and var'ing it again makes no difference - it was, and always will be, a local variable.

See What does "options = options || {}" mean in Javascript? for use of seed || .. in general.

Upvotes: 2

David Conrad
David Conrad

Reputation: 16359

Assuming you're referring to seed = seed || { object literal }, the purpose is to provide a default value for seed in case the function was called without that parameter (or with undefined for that parameter, or any other falsy value).

If seed is present, it will have the value that was passed in, but if it is undefined (or null, 0, false, etc.), then an object will be supplied for it.

Upvotes: 0

Sterling Archer
Sterling Archer

Reputation: 22395

The points variable is an empty array.

Upvotes: 0

Related Questions