JavaScript for WordPress › Forums › Vanilla JavaScript › is for loop better than for of ?
- This topic has 3 replies, 2 voices, and was last updated 8 years, 6 months ago by
Zac Gordon.
-
AuthorPosts
-
April 15, 2017 at 4:48 pm #25753
Alexandra
ParticipantHi,
when i was on the reverse engineer phase of vanilla press i used a for of loop
i see you use a for loop, is it a reason for this ? as i found the for of loop much more simpler ( i also noticed that the for in loop doesn’t work, but i don’t know exactly why)view.loadBlogPosts = function () { var posts = model.getPosts(), postsMarkup = document.createDocumentFragment(), primaryContentEl = helpers.getPageContentEl(); for (var post of posts) { postsMarkup.appendChild(view.createPostMarkup(post)); } primaryContentEl.appendChild(postsMarkup); };and
model.getPost = function (slug) { var posts = model.getLocalStore(); for (var post of posts) { if(slug === post.slug){ return post; } } return null; };well my code was much more messy, and i was stucked after the part of displaying all the posts (but super happy to get there alone!)
April 15, 2017 at 5:49 pm #25767Zac Gordon
KeymasterI used the for loop just to make it as a simple as possible in terms of using Vanilla JavaScript.
While technically the for loop may be a little faster to execute, the for in or for of loops are much cleaner to write.
I would suggest using for in and for of when they are appropriate.
As for your question about for in not working, it should work if you’re using it correctly. I don’t see an example of for in above tho, only for of. Is that what you meant?
April 15, 2017 at 6:17 pm #25770Alexandra
Participantin the functions i have tried to put in instead of of
view.loadBlogPosts = function () { var posts = model.getPosts(), postsMarkup = document.createDocumentFragment(), primaryContentEl = helpers.getPageContentEl(); for (var post in posts) { postsMarkup.appendChild(view.createPostMarkup(post)); } primaryContentEl.appendChild(postsMarkup); };And it doesn’t work , title and content are displayed as undefined, why ?
April 15, 2017 at 6:36 pm #25777Zac Gordon
KeymasterAh, I think you want to use the for of loops in this case. The for in loop is for looping through properties of an object, not so much for loops through items in an array.
Is that it?
-
AuthorPosts
- You must be logged in to reply to this topic.
