JavaScript for WordPress Forums Vanilla JavaScript is for loop better than for of ?

Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #25753
    Alexandra
    Participant

    Hi,
    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!)

    #25767
    Zac Gordon
    Keymaster

    I 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?

    #25770
    Alexandra
    Participant

    in 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 ?

    #25777
    Zac Gordon
    Keymaster

    Ah, 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?

Viewing 4 posts - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.