array .some( function(value, index, arr), this )
Can someone please explain the purpose of index, arr and this?
I think I understand that value returns truthy or falsey, but how do I output the index?
And what does ‘this’ have to do with anything? Here is an example from Codecademy:
const words = [‘unique’, ‘uncanny’, ‘pique’, ‘oxymoron’, ‘guise’];
// Something is missing in the method call below
console.log(words.some((word) => {
return word.length < 6;
}));
In this example, pique is the 1st value that has < 6 letters. That would be index 2. How do I return that to the console? That’s what the index parameter is for right?
The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn’t modify the array.
Which means, you have an array myArray, and you have a function that checks a condition check(). When you call myArray.some(check); you will get a boolean return on whether at least one element of myArray met the condition outlined in check().
It’s completely optional. This is a very common pattern in js (for the fp functions).
The function iterates on an array, as it iterates, it goes through value-index pairs.
So A = [x,y,z] is going to iterate x: 0, y:1, z:2. arr will always be [x,y,z].
In terms of what it’s good for in this case… it depends.
Toy example: Imagine you have an array A = [“0”, “1”, “10”, “11”, “100”, “x”], and you want to check if there is an element that is not the binary string representation of the index.
In terms of purpose, think about what a for-loop gives you. You can iterate over a range of numbers and have full access to an array thanks to those. So you have access to: indices, elements of array at those indices, the array itself. Plus you write whatever code you want.
In javascript (and other multi-paradigm languages + functional ones), you have special functions that aim to have a more granular usage. Like filter(), reduce(), some(). These are like for-loops for very specific purposes. You still want to have control over indices, elements, and the array… but when people (or you) read your code and they see you invoke the function they can quickly deduce the reason why you wrote it.
tl;dr: it’s a concise functional style for for-loops.
Well, flip the question, is it useful to have indices while iterating? Ever? If it is, that’s why you have it. What if you wanted to check that every word is larger than the word to the left of it?
words = ['a', 'be', 'cat', 'doge']
You can create a function, is the value at i-1 bigger? But for that you need an index…