JavaScript for WordPress Forums Vanilla JavaScript 1.3.05 – confusion with newContent

This topic contains 2 replies, has 2 voices, and was last updated by  Zac Gordon 3 years, 5 months ago.

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #7902

    Michael Davies
    Participant

    Hi guys

    I’m having some minor confusion on the second part of lesson 1.3.05. In the app.js file, on line 40 it assigns content with the query selector as follows:

    var content = document.querySelector( ‘.content’ ),
    newContent;

    What is the purpose of the “, newContent;” here? I’ve not seen a command assigned this way before. Have tried deleting it and it looks like it still works, so is it a typo? Or am I missing something important?

    Cheers!

    Mike

    #8146

    Zac Gordon
    Keymaster

    Hi Mike!

    Yes, this is a leftover from a different demo that got left in the source code. I will make a note and remove it 🙂

    You may also want to rewatch some of the earlier videos in 1.2 where it talks about best practices for writing variables. This is a practice where you name and declare the variable at the top of your code even if you might not assign it a value till later. This way are variables are declared in one place for organization purposes.

    We will relook at this when we get to scope a bit later in the course.

    #8264

    Zac Gordon
    Keymaster

    Hi Mike,

    When I went back to fix this I realized that actually newContent should be there.

    As mentioned, there is a best practice to declare all variables at the top of a section of code even if you do not assign them values until later. Later in the code you will note that newContent is assigned a value. However, the best practice is to declare all of your variables at the top and the assign them specific values later on. So, this code you pointed out is actually correct.

    Later in the course we will get into why it still seems to work when you don’t declare it first as a variable, and it has to do with the topic of Scope.

    Thanks!

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.