Home > Mobile >  Typescript .forEach and for in behavior
Typescript .forEach and for in behavior

Time:10-26

I made a Typescript playground to show you the code and the output. I don't understand why I don't have the same result in my code when I'm using .forEach and for in loop.

I made 2 functions to trim all body parameters. The first function use .forEach() and the 2nd use for in.

Here is the functions:

function trimWithForEach(obj: any): any {
    if (obj !== null && typeof obj === 'object') {
        Object.keys(obj).forEach(function (prop) {
            // if the property is an object trim it
            if (typeof obj[prop] === 'object') {
                return trimWithForEach(obj[prop]);
            }

            // if it's a string remove begin and end whitespaces
            if (typeof obj[prop] === 'string') {
                obj[prop] = obj[prop].trim();
            }
        });
    }
}

function trimWithForIn(obj: any): any {
    if (obj !== null && typeof obj === 'object') {
        for (var prop in obj) {
            // if the property is an object trim it
            if (typeof obj[prop] === 'object') {
                return trimWithForIn(obj[prop]);
            }

            // if it's a string remove begin and end whitespaces
            if (typeof obj[prop] === 'string') {
                obj[prop] = obj[prop].trim();
            }
        }
    }
}

With the forEach() I have the good result that I want, it will trim all my body. But with for in I have a problem because only the first object conditon is triggered to make my recursive call and if I have other object types they are ignored. The recursive call works only once in all my body object in the for in loop and I don't know why.

Can you help me to understand ?

CodePudding user response:

In for..in loop the return is returning you out of function at the very first time it encounters the condition to be true. That's why the later items never get processed.

I am not quite sure what you are trying to do here but there is a basic difference between the way 'forEach' and 'for...in' works with regards to 'return'.

In for...in return returns the value out of function, but in forEach the return doesn't work.

Look at the following simple example for more clarity

var testfn = function() {
  let a = [1,2,3]
  let b =  a.forEach(el => {
    if ( el == 2 )
      return el
  })
  console.log("Came here!")
  console.log({b})
}

var testfn1 = function() {
  let a = [1,2,3]
  for ( let i in a ){
    if ( a[i] == 2 )
      return a[i]
  }
  console.log("Came here!")
  console.log({a})
}
testfn()
testfn1()
  • Related