startsWith is not a function getting called for no reason I can think of

value[i].keyword.startsWith("keyword") because the parameter of start with must be a string. So that will work better this way

for (var i = 0; i < value.length; i++) {
     if (typeof value[i].keyword == String(undefined) || value[i].keyword.startsWith("keyword"))
         out.push(value[i]);
}

Is there a way that I can check if it's a string rather than have it error out?

checking the type?

var out = values.filter(v => v.keyword == null || typeof v.keyword === "string" && v.keyword.startsWith( keyword ));

or simply enforcing the type

var out = values.filter(v => v.keyword == null || String(v.keyword).startsWith( keyword ));

or if you use desctructuring, you can use even this:

var out = values.filter({keyword: v}) => v == null || String(v).startsWith( keyword ));

I'd reccomend you to use the Array-methods instead of manually writing loops.

  • Imo. it is a better description of your intent (good for scanning over code).

  • If this is a hot path (it's called often) the JS-optimizer can take advantage of knowing, that youre'just filtering, and optimize the code. Maybe by skipping the lots of integrity-checks for the Array it performs during your loop.

  • And if this is not a hot-path, the performance-impact of calling a function a few times will even be hard to measure, in JS.


Found a useful article on this topic

The three approaches for converting to string are:

  1. value.toString()
  2. "" + value
  3. String(value)

The point to note here is that approach # 1 doesn’t work if the value is null or undefined.

In my case, approach # 2 for some reason did not work either so the best option would be String(value)

var col = "rt_" + rows[i]["results"][r].ResultTypeID.substring(1); //did not work

var col = "rt_" + String(rows[i]["results"][r].ResultTypeID).substring(1);

Tags:

Javascript