DEV Community

Artem Verbitski
Artem Verbitski

Posted on • Edited on

10 Popular JavaScript methods implemented from scratch

Introduction

In this article I wanted to share with you with the most popular JavaScript methods but implemented by scratch.
A little understanding of how JavaScript methods works inside will always help you as a developer.
So these are the most popular methods in JavaScript implemented from scratch. Check this out if you are interested how JavaScript methods works inside. This is also a light version of how this work, the real method specified in ECMAScript is much more complex.

Methods mentioned on this article are:

map, reduce, filter, sort, every, includes, slice, splice, shift, indexOf.

1. map()

const fakeMap = function (callback) {
  const newArray = [];

  // 'this' refers to the array
  for (let i = 0; i < this.length; i++) {
    newArray[i] = callback(this[i], i);
  }

  return newArray;
};
Array.prototype.fakeMap = fakeMap;

[1, 2, 3].fakeMap((n) => n + 1); // output [2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

2. reduce()

const fakeReduce = function (callback, accumulator) {
  for (let i = 0; i < this.length; i++) {
    accumulator = callback(accumulator, this[i]);
  }
  return accumulator;
};
Array.prototype.fakeReduce = fakeReduce;

const reducer = (previousValue, currentValue) => previousValue + currentValue;

[1, 2, 3].fakeReduce(reducer, 0); // output 6

Enter fullscreen mode Exit fullscreen mode

3. filter()

const fakeFilter = function (callback) {
  const newArray = [];

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

  return newArray;
};

Array.prototype.fakeFilter = fakeFilter;

[1, 2, 3, 4, 5].fakeFilter((n) => n > 2); // output [3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

4. sort()

const fakeSort = function (callback) {
  const newArray = [...this];

  for (let i = 0; i < newArray.length; i++) {
    for (let j = 0; j < newArray.length - 1; j++) {
      if (callback(newArray[j], newArray[j + 1]) > 0) {
        const temp = newArray[j + 1];
        newArray[j + 1] = newArray[j];
        newArray[j] = temp;
      }
    }
  }

  // array is sorted
  return newArray;
};

Array.prototype.fakeSort = fakeSort;

[3, 5, 1, 4, 2].fakeSort((a, b) => a - b); // output [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

5. every()

const fakeEvery = function (callback) {
  for (let i = 0; i < this.length; i++) {
    if (!callback(this[i])) {
      return false;
    }
  }

  return true;
};

Array.prototype.fakeEvery = fakeEvery;

[1, 2, 3, 4, 5].fakeEvery((n) => n > 3); // output false
Enter fullscreen mode Exit fullscreen mode

6. includes()

const fakeIncludes = function (item) {
  for (let i = 0; i < this.length; i++) {
    if (this[i] === item) {
      return true;
    }
  }

  return false;
};

Array.prototype.fakeIncludes = fakeIncludes;

[1, 2, 3, 4, 5].fakeIncludes(5); // output true
Enter fullscreen mode Exit fullscreen mode

7. slice()

const fakeSlice = function (start, end) {
  let newArray = [];
  if (!end) {
    for (let i = 0; i < this.length; i++) {
      if (i >= start) {
        newArray.push(this[i]);
      }
    }

    return newArray;
  }

  for (let i = 0; i < this.length; i++) {
    if (i >= start && i <= end) {
      newArray.push(this[i]);
    }
  }
  return newArray;
};

Array.prototype.fakeSlice = fakeSlice;

[1, 2, 3, 4, 5].fakeSlice(2, 3); // output [3, 4]
Enter fullscreen mode Exit fullscreen mode

8. splice()

const fakeSplice = function (start, deleteCount, ...items) {
  let newArray = [];

  // if we only provide start fakeSplice(start)
  if (!deleteCount) {
    for (let i = 0; i < this.length; i++) {
      if (i < start) {
        newArray.push(this[i]);
      }
    }
    this.length = 0;
    this.push.apply(this, newArray);
    return;
  }

  // if we only provide start and deleteCount fakeSplice(start, deleteCount)
  if (!items) {
    for (let i = 0; i < this.length; i++) {
      if (i < start || i >= start + deleteCount) {
        newArray.push(this[i]);
      }
    }

    this.length = 0;
    this.push.apply(this, newArray);
    return;
  }

  // if we provide all arguments to the function
  for (let i = 0; i < this.length; i++) {
    if (i === start + deleteCount) {
      newArray = [...newArray, ...items];
    }
    if (i < start || i >= start + deleteCount) {
      newArray.push(this[i]);
    }
  }

  this.length = 0;
  this.push.apply(this, newArray);
  return;
};

Array.prototype.fakeSplice = fakeSplice;

const planets = [
  "Mercury",
  "Venus",
  "Earth",
  "Mars",
  "Jupiter",
  "Saturn",
  "Uranus",
  "Neptune",
];
planets.fakeSplice(2, 2, "Pluto");
console.log(planets); // output ["Mercury", "Venus", "Pluto", "Jupiter", "Saturn", "Uranus", "Neptune"]

Enter fullscreen mode Exit fullscreen mode

9. shift()

const fakeShift = function () {
  let newArray = [];

  for (let i = 1; i < this.length; i++) {
    newArray.push(this[i]);
  }

  this.length = 0;
  this.push.apply(this, newArray);
};

Array.prototype.fakeShift = fakeShift;
const arr = [1, 2, 3, 4, 5];

arr.fakeShift();
console.log(arr); // output [2, 3, 4, 5]

Enter fullscreen mode Exit fullscreen mode

10. indexOf()

const fakeIndexOf = function (item) {
  for (let i = 0; i < this.length; i++) {
    if (item === this[i]) {
      return i;
    }
  }
  return -1;
};

Array.prototype.fakeIndexOf = fakeIndexOf;

[1, 2, 3, 4, 5].fakeIndexOf(4); // output 3

Enter fullscreen mode Exit fullscreen mode

Conclusion

We just implemented the most used methods in JavaScript and get a better understanding of how they work so we can use them more effectively.

Thank you for your time!

Top comments (16)

Collapse
 
northwillov profile image
Artem Verbitski

Yes, I totally agree with you.
You don't have to know how car engine works inside to drive a car, what I meant was
knowing how car engine works, makes you a better understanding of a car itself.

And you may be surprised but assembly language is still in use, so knowing such stuff definitely makes you a better dev 😜.

Cheers!

 
northwillov profile image
Artem Verbitski

These are only a light versions of "the engine". So we won't get a full understanding of it, but a light one.

For those who want to familiarize with the internals of JS methods e.g. Array.prototype.map you can find this information here: developer.mozilla.org/en-US/docs/W...

Thanks 😀

Collapse
 
antongolub profile image
Anton Golub

sort should work in place:

10. Repeat, while j < itemCount,
a. Perform ? Set(obj, ! ToString(𝔽(j)), items[j], true).
b. Set j to j + 1.
Enter fullscreen mode Exit fullscreen mode

tc39.es/ecma262/#sec-array.prototy...
developer.mozilla.org/en-US/docs/W...

Collapse
 
northwillov profile image
Artem Verbitski • Edited

Hi!
These are only a light versions of popular methods in JS, and of course the original methods mentioned in ECMAScript are much more complex and useful.
Thank you for comment :)

Collapse
 
biglogic profile image
Big-Logic

Nice. Fundamentals are worth knowing. Developers are like engineers who build engines, so if you don’t understand how a single part of the engine you want to build works, than you are going to be some kind of mere dev because trial and error are what you are going to be on all times.

Collapse
 
lepinekong profile image
lepinekong

It's not the same thing as rebuilding a car engine, but it shows he knows javascript and datastructure. Sometimes you need an original algorithm if you software is a bit innovative, if you just do lame integration work then it's ok you don't need to understand much.

 
lepinekong profile image
lepinekong • Edited

I don't say ALL integration work are lame, I say that there are integration work that are lame that's why they are automatable why do you think lowcode/nocode are now rising and usable by just business people ;) dev.to/lepinekong/comment/1l7ab

Collapse
 
prabhukadode profile image
Prabhu

Useful

Collapse
 
oskarcodes profile image
Oskar Codes

Good article, but you forgot to include the return -1 for .indexOf

Collapse
 
northwillov profile image
Artem Verbitski

Thanks for noticing! I made an update.

 
lepinekong profile image
lepinekong • Edited

I do SystemThinking : things are not separate ;) If I recruit a coder I will indeed want to be sure he master the fundamentals if not I would rather recruit the guy/girl for doing lowcode or nocode.

Collapse
 
the_yamiteru profile image
Yamiteru

Are these implementations faster than native ones?

Some comments may only be visible to logged-in visitors. Sign in to view all comments. Some comments have been hidden by the post's author - find out more