skip to Main Content

JavaScript: Looping through objects – for loop or .forEach()

I’m working with JavaScript and need to loop through an array of objects. I want to check if a specific property exists within each object. I’m unsure whether to use a traditional for loop or the .forEach() method for this task. Could someone explain the advantages and disadvantages of each approach in this scenario?

2

Answers


  1. There isn’t much difference besides how you want your syntax to look.

    For loop will just loop over a index and you can define functionality inside but you must reference by index.

    For each will allows you to define a callback function for each element you are looking at in the loop. So if you leave it as just a variable it will be just a variable.

    https://www.geeksforgeeks.org/difference-between-foreach-and-for-loop-in-javascript/

    Checking for a specific property you might be better using .find since it will create a array with just the elements that have the property you want.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

    Login or Signup to reply.
  2. You can use either for..of or .forEach on your array and there wouldn’t be much difference, but as someone else mentioned, there are some built-in functions that should make it possible to accomplish your goal without needing a loop at all. (BTW, forEach technically isn’t a "loop" either but it’s certainly loop-like.) It would be easier to answer your question if you had provided some code that you had tried, but supposing you have an array of objects something like this:

    const objArray = [ {foo: 1}, {foo: 2}, {bar: 2} ]
    

    If you wanted to check if every object has a foo property, you could do this:

    objArray.every(obj => 'foo' in obj)
    

    Or this:

    objArray.every(obj => obj.hasOwnProperty('foo'))
    

    These would both return false for the above example, because the last object doesn’t have a foo property.

    The only difference between the in keyword and calling hasOwnProperty is that in will include the object’s prototype, which is relevant if you’re dealing with objects defined using inheritance (e.g. a class that extends another class) or native properties. Personally I would just use in in this case but people have different opinions on it and it depends on what you know about the objects you’re dealing with; you can read more about inheritance in JS here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain.

    Note that both methods only check if the property is defined in the object, which is what you asked, but I’m just mentioning this because FYI they will return true even if the value of the property is set to null or explicitly set to undefined (e.g. {foo: undefined}).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search