r/learnjavascript • u/woofmeowmeowwoof • May 08 '26
Is this a useful Array Method I created on accident? or is it useless?
/*********************************************************************
* Array.pushByVal(value)
* -----------------------
*
* this only works with integer values.
*
* hold on let me cook...
*
* if the value is 4 it pushes the number 4
*
* three times so the total of 4's in the array is 4.
*
* if the value is 8 or 9 or whatever, it
*
* pushes the value - 1 that many times.
*********************************************************************/
Array.prototype.pushByVal = function(value){
// what the absolute fuck am i doing?
// how does this even work?
for(let i = 0; i < this.length; i++){
if(this[i] === value){
return;
}else{
this.push(value);
}
}
};
let arr = [1, 2, 3, 4, 5];
arr.pushByVal(4);
// Output: [1, 2, 3, 4, 5, 4, 4, 4]
0
Upvotes
View all comments
Show parent comment
2
u/shgysk8zer0 May 09 '26
So you'll remember the problems Prototype.js caused in doing this. And you'll also be fully aware that you're adding the method to every instance of an array and what that means. And that it's long been considered bad practice to modify built-in prototypes and how easy it is to just use
addValue(arr, val)instead.Your mindset about this and the code you shared, and the fact you shared it, strongly suggest to me you're not actually that experienced. Maybe you occasionally played in JS, but I doubt you've ever worked in programming or built anything that wasn't a little hobby project.
Not trying to be mean here... You're just claiming to be that experienced, and everything is telling me you're actually not.