-1

I do not seem to understand why I cannot return the following values. I want to use custom colors for coloring a bar chart.

function farbe() {
  d3.csv("./Barchart_Farben.csv", function(data) {

    farbdat = new Array;
    for (var i = 0; i < data.length; i++) {
        farbdat.push(data[i].Farbe);
    }
      console.log(farbdat);
      return(farbdat);      
  });
  };

console.log(farbe());

Output:

undefined

Array(5) [ "yellow", "violet", "orange", "red", "lightyellow" ]

Nothing gets returned. Why?

// ./Barchart.csv: 
// Farbe 
// yellow
// violet
// orange
// red
// lightyellow
Community
  • 1
  • 1
Krisselack
  • 503
  • 3
  • 16
  • 3
    As I like to say, there are two types of programmers: *...and those who don't. Those who understand asynchronous code...* – Gerardo Furtado Mar 01 '19 at 02:30
  • 1
    Thanks, now I kind of understood what's going on! – Krisselack Mar 01 '19 at 08:28
  • 2
    That's good. And please don't get offended by my joke, I never meant to be rude. I love that joke! I read it somewhere, I don't remember where, but it captures nicely the nature of an asynchronous code. – Gerardo Furtado Mar 01 '19 at 08:32

2 Answers2

0

I guess d3.csv function doesn't return anything. Try this.

function farbe() {
  var returnData = [];
  d3.csv("./Barchart_Farben.csv", function(data) {

    farbdat = new Array;
    for (var i = 0; i < data.length; i++) {
      farbdat.push(data[i].Farbe);
    }
    console.log(farbdat);
    returnData = farbdat;
  });
 return returnData;
};

you must check typeof and undefined for input parameter 'data' before looping on it.

Deepak gupta
  • 504
  • 1
  • 6
  • 22
-1

return is not a function, is a statement. You should write return farbdat instead of return(farbdat).

brubs
  • 1,259
  • 8
  • 23
  • Why the downvote? Please add a reason. – brubs Feb 28 '19 at 11:49
  • Thanks, but did not work. – Krisselack Feb 28 '19 at 12:30
  • 2
    Agreed, [`return`](https://www.ecma-international.org/ecma-262/9.0/index.html#prod-ReturnStatement) is a statement. But that statement returns the value of an expression following the `return` keyword. `(farbdat)`, on the other hand, is a perfectly fine expression which is basically the same as `farbdat` itself. Sure, it may look weird and it may be an indication that an inexperienced coder is off the track but the code is valid. The problem is a completely different one, namely asynchronous execution. – altocumulus Feb 28 '19 at 13:51
  • @altocumulus Cool, thanks for the explanation! I did not see that. – brubs Mar 01 '19 at 08:50