Question about javascript and callback prototype

Question about javascript and callback prototype
0

#1

Hello, here an exemple from this exercice:
link:https://beta.freecodecamp.org/en/challenges/functional-programming/implement-the-filter-method-on-a-prototype

Ok, of what i think i understand is that the “s” variable correspond to the “this” and itself correspond to the Array from prototype. It does make sens for me. But the “callback”, it’is the “item” variable ? and foreach “callback( this[x] ) == 1”,
it push it in an new array?

I figured out the exercice because of a previous exemple using callback so i re-adapted it with my own touch (xD) and it worked. But i feel like i playing with dangerous material. It feel uncomfortable, and most importantly in the long run.


var s = [23, 65, 98, 5];

Array.prototype.myFilter = function( callback ){
	var newArray = [];

  	for( let x = 0; x < this.length; x++ ) {
		if( callback( this[x] ) == 1 ) {
			newArray.push( this[x] );
		}
	}
	
	return newArray;
};

var new_s = s.myFilter( function( item ){
	return item % 2 === 1;
} );

console.log( new_s );

#2

function(item){ ... } is what you pass as parameter to the filter function. So callback is that function you pass in.

callback(this[x]) is calling that function where this[x] is passed for the item parameter.


#3

note that generally a filter only keeps the values for which the callback returns true or a truthy value. I think adding the == 1 in your if complicates things and won’t make it work like the native .filter, as 1 and truthy values will not be equal in most cases. Simply using

if (callback(this[x])) { 

would be an improvement.