Jim Johnson
Jim Johnson

Reputation: 2609

Why are some JavaScript variables accessed by placing a 0 right after the variable name?

Let's say you have an object literal:

var d = {
    x: +'35',
    y: '25'
};

And an anonymous function:

function (d) {
    return d.y0 + d.y;
}

When I experiment with this code, I get "undefined" in place of d.y0. But there is plenty of d3.js code that accesses a value by appending 0 to its key. What does this 0 do?

Upvotes: 0

Views: 101

Answers (2)

Simon MᶜKenzie
Simon MᶜKenzie

Reputation: 8684

Looking at the javascript source from your link, y0 is an internal designation used in d3 to refer to the y coordinate of the first point in your collection of data, e.g.:

function d3_svg_lineBundle(points, tension) {
  var n = points.length - 1;
  if (n) {
    var x0 = points[0][0],
        // Here
        y0 = points[0][1],

or

function d3_svg_lineBasis(points) {
  if (points.length < 3) return d3_svg_lineLinear(points);
  var i = 1,
      n = points.length,
      pi = points[0],
      x0 = pi[0],
      // Here
      y0 = pi[1],

There's definitely nothing special about appending '0' to property names!

Code samples are from this js file: http://mbostock.github.com/d3/d3.js?1.29.1

Upvotes: 2

David G
David G

Reputation: 96845

In JavaScript, d.y0 is undefined unless d has a property named y0. I'm not familiar with d3 but if it uses pure JavaScript then the only way they can reference properties with an appended 0 is if the objects from which they're referencing the properties have a property with that name.

Upvotes: 2

Related Questions