ITNEXT

ITNEXT is a platform for IT developers & software engineers to share knowledge, connect, collaborate, learn and experience next-gen technologies.

Follow publication

Member-only story

You may need Laziness in your Javascript (Lazy Evaluation)

6 min readFeb 22, 2019

--

Maybe some times you have overused the Array methods map, reduce, filter, find, etc. and that could make out applications to use more memory of what they should be using.

Let’s see an example:

const myArray = [1,2,3,4,5,6,7,8,9,10]myArray
.map(x => x * x)
.filter(x => x % 3 === 0)

Sure you have done something similar to this several times, and what is the “problem” here, we are creating new arrays every time we chain and array method. That means the .map creates another array with the x² in every index ([ 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 ]) and after that create another filtered one [ 9, 36, 81 ] in this case you maybe don’t have any problem of performance of memory use, but what if myArray is a very large one? you are going to create another big one again, and again until you have your wanted result.

In those cases, the Lazy evaluation with iterables could be useful. But first, how can we create an iterator and how works.

What is an iterator?

An iterator is an Object that defines a sequence and maybe return a value when the sequence is finished, those sequences could be Finite or Infinite.

--

--

ITNEXT
ITNEXT

Published in ITNEXT

ITNEXT is a platform for IT developers & software engineers to share knowledge, connect, collaborate, learn and experience next-gen technologies.

Sergio Marin
Sergio Marin

Written by Sergio Marin

Software developer focused on efficiency, minimalism, and optimizing workflows. Sharing insights from personal projects and development experiments.

Responses (2)

Write a response