Introduction to Iterators


#1

This was the code in the main.js in the Introduction to Iterators section from the course. In the code below, is there an inconsistency with ‘thing’ (as in is it supposed to be typed as the things array?) Isn’t number a string? Are we telling the function to return any condition that’s a thing as long as it is a string as ‘number’ or does this refer to a data type?

Sorry if this did not make sense I’ve been learning code for a short time now.

// let things = [‘desk’, ‘chair’, 5, ‘backpack’, 3.14, 100];

let onlyNumbers = things.filter(function(thing) {
return typeof thing === ‘number’;
});

console.log(onlyNumbers);


#2

Since the declaration is commented, absence of the above line will raise a reference error. The filter function does not return anything.

let things = [‘desk’, ‘chair’, 5, ‘backpack’, 3.14, 100];
let onlyNumbers = things.filter(function(thing) {
  return typeof thing === ‘number’;
});

On first run, got this error…

console.log(onlyNumbers);    //->  SyntaxError: Unexpected character '‘' (14:14)

The quotes on your strings are not ' or ". After fixing that,

console.log(onlyNumbers);    //->  [ 5, 3.14, 100 ]

For practice with ES6+,

let onlyNumbers = things.filter(thing => typeof thing === 'number');

#5

Ok, thank you for the help.

I add the ‘//’ purposefully for the forum, I see how that would be confusing.

I’m so glad you pointed that out the mistake with the backsticks.

Is the ‘number’ going to allow the .filter to recognize the number data types?


#6

In the context of typeof, yes. There are other ways to determine if a value is a number, but for this purpose, typeof fits the bill.

The key to remember about filter is that the interation and conditional are built in.

Try this one:

let onlyNumbers = things.filter(thing => Number(thing));

In evaluating a condtional expression, JavaScript coerces the value in the expression to best fit the scenario. It will try to cast a string as a number but will not succeed if the string is not digits with perhaps a sign and decimal point. It will then respond with NaN. Since NaN is not truthy, the value in the list is passed over.

Try wrapping 3.14 in quotes. The result will be,

[ 5, '3.14', 100 ]

Note that we do not operate on the values in the array, only test them. If the conditional yields true, the value from the array is appended to the filtered array which is the return value of this method.

Here’s another one to try,

let onlyNumbers = things.filter(thing => +thing);

Same result as before. + is the unary operator for coercing a value to a number. If the value cannot be converted, then it becomes NaN.

One thing to note, typeof will not recognize ‘3.14’ as a number, but a string.

[ 5, 100 ]