What is the purpose of selectAll('rect') here if it was empty anyway

Link to challenge: https://www.freecodecamp.org/learn/data-visualization/data-visualization-with-d3/change-the-color-of-an-svg-element

I actually don’t have any problem specific to solving this current challenge. But I am unable to understand why this is the case, that the code templates svg.selectAll("rect") here when rect tags does not exist in the document.
I have noticed that removing .selectAll('rect') here actually does not show any output. Also, changing the name of rect here to any random string also gives same output with same style too… :roll_eyes: :face_with_monocle:
I think that it was just to create an empty array at that place. If that was so, using selectAll() actually reduces readability of the code. Is there no better way of doing the same thing without selectAll()?

    const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];

    const w = 500;
    const h = 100;

    const svg = d3.select("body")
                  .attr("width", w)
                  .attr("height", h);

    svg.selectAll("rect")   //THIS LINE
       .attr("x", (d, i) => i * 30)
       .attr("y", (d, i) => h - 3 * d)
       .attr("width", 25)
       .attr("height", (d, i) => 3 * d)
       // Add your code below this line

       // Add your code above this line

Docs are your friend here: data, selectAll. The key is that the call to data() creates a new selection of objects created from the data array. The idiom

  .attr('class', 'bar')

is a common way to loop (implicitly) over some data creating (or updating) SVG (DOM) elements with attributes from the data.

For further reading, D3’s creator has an article about it as well in which he calmly assures us that it’s not magic.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.