12

In the official Vue.js documentation, all of the examples for the v-for directive have the format:

v-for="thing in collection"

where collection includes arrays and objects. Further, the documentation states:

You can also use of as the delimiter instead of in, so that it is closer to JavaScript’s syntax for iterators.

This answer explains the difference between for..in and for..of loops in vanilla JavaScript. As I understood it, for..in is used to loop over an object's properties and for..of is used to loop over an iterable's elements.

My question is, do of and in carry the same meaning in Vue as they do in vanilla JavaScript?

tony19
  • 125,647
  • 18
  • 229
  • 307
Aditya Barve
  • 1,351
  • 1
  • 9
  • 13
  • did you try with any sample data and check in vanilla and vuejs both ? if yes please share? – Niklesh Raut Dec 31 '18 at 08:01
  • The [answer is here](https://github.com/vuejs/vue/issues/2410), and this article about Vue v3 and how it will support new data types for `v-for` [Article](https://medium.com/the-vue-point/plans-for-the-next-iteration-of-vue-js-777ffea6fabf) – Moumen Soliman Dec 31 '18 at 08:33

1 Answers1

11

They do not

In Vue.js, for..of and for..in are equivalent and interchangeable. Iterating in Vue.js is very flexible and can handle a wide variety of objects and types (Even integers! Take note, TC39!).

https://v3.vuejs.org/guide/list.html

The following is valid Vue.js code:

<p v-for="x of {a: 1, b: 2, c: 3}">{{x}}</p>
<p v-for="x in {a: 1, b: 2, c: 3}">{{x}}</p>
  
<p v-for="x of [1, 2, 3]">{{x}}</p>
<p v-for="x in [1, 2, 3]">{{x}}</p>

All of these will print out 1, 2, 3.

In plain JavaScript, however, there is a difference between for..of and for..in.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

The important difference is that for..of will iterate over iterable objects, where for..in will iterate over enumerable properties.

for (const x of {a: 1, b: 2, c: 3}) {console.log(x);} // TypeError ... is not iterable
for (const x in {a: 1, b: 2, c: 3}) {console.log(x);} // Prints a b c

for (const x of [1, 2, 3]) {console.log(x);} // Prints 1 2 3
for (const x in [1, 2, 3]) {console.log(x);} // Prints 0 1 2 (the indexes)

As you can see, they behave very differently.

Even what might look like the same code (for..in {a: 1, b: 2, c: 3}) will yield different results in Vue.js and plain JavaScript, one will print 1, 2, 3, the other a, b, c.

Ionaru
  • 982
  • 3
  • 13
  • 23