DEV Community

Zach
Zach

Posted on

be careful with .forEach()

I finally got around to solving one of the toy problems that I couldn't completely solve in the pre-course the diagnostics.

My issue was that I didn't understand the behaviors of .forEach() loops.

I was expecting a return statement to break out of the loop, but that's not what .forEach() is for. forEach() is used when you want to iterate over all of the items in your array. 'Return' in this case only breaks out of the current function but the loop resumes. The only way to break out of .forEach() loops is to throw an exception.

Instead of using .forEach(), in this case, a better tool is a simple for or while loop. These lend themselves perfectly for catching certain cases and then, for instance, returning out of them.

I'll show the buggy code first and then my work-around (storing the a boolean in a variable). If I was re-factoring this, I would ditch the .forEach() in favor of a 'for' loop.

Broken:

var isIPv4Address = function(inputString){

  var ip4 = inputString.split('.')
  ip4 = ip4.filter(item => item !== '')
  ip4 = ip4.map(item => Number(item)).filter(item => String(item) !== 'NaN')

  if (ip4.length !== 4) return false


  ip4.forEach(function(item){
    if (item > 255) {
    return false
  })
}
var a = '213.234.234.344'
console.log(isIPv4Address(a))
Enter fullscreen mode Exit fullscreen mode

Working:

var isIPv4Address = function(inputString){

  var isAddress = true;

  var ip4 = inputString.split('.')
  ip4 = ip4.filter(item => item !== '')
  ip4 = ip4.map(item => Number(item)).filter(item => String(item) !== 'NaN')

  if (ip4.length !== 4) isAddress = false

  ip4.forEach(function(item){
    if (item > 255) isAddress = false
  })

  return isAddress
}
var a = '203.294.234.234'
console.log(isIPv4Address(a))
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
daviot profile image
Daviot

Hi
Solid solution, you could also use .some((item, index,arr)=>{return item > 255}). Which returns an boolean.
Sorry for commenting on your note.

Collapse
 
zbretz profile image
Zach

Thanks for adding that. Yeah that's a nice way of applying what i've learned to call 'functional programming'. Functions like filter/reduce/etc and .some are pretty slick. This is a great use of it. Really nice. Thanks!

Collapse
 
zbretz profile image
Zach

I used .some today!

Wrote a sentence or two about it here. Just thought I'd send you a thanks for sharing it with me.