Is there any difference between .map or .foreach when iterating in simple functions?

When accomplishing simple object iteration, should I write my code like this:

  @OntologyEditFunction()
    @Edits(sampleObject)
    @Function()
    public async marksampleObject(
       ObjSet: ObjectSet<sampleObject>
    ): Promise<void>{
        const objects = await sampleObject.allAsync();
        objects.forEach( (obj) => {
            obj.prop = true;
        })
    }

or

  @OntologyEditFunction()
    @Edits(sampleObject)
    @Function()
    public async marksampleObject(
       ObjSet: ObjectSet<sampleObject>
    ): Promise<void>{
        const objects = sampleObject.all();
        objects.map( (obj) => {
            obj.prop = true;
        })
    }

Which is cleaner/faster?

using .map will create return a new array based on the inputs and logic specified, .forEach will modify the array in place.

For example, if you wanted to perform async functions on a list of objects here, you should use .map to return a list of promises, and await them all at once.

4 Likes