-2

I'm following some courseware which has a code example which works, but makes no sense. I've read it's good coding practice to use "var" when defining variables, but this example seems to not work when using the "var" statement.

function initiate()
{
    content=document.getElementById("secContent");
    var button=document.getElementById("send");
    button.addEventListener("click", read, false);
}

The code above works, but using the same code and adding "var" at the "content=document.getElementById..." breaks it.

I'm wanting to understand why this seemingly subtle difference makes such a big difference.

Zerkie
  • 1
  • 1
    Likely because `content` is already defined outside the function's scope in the same context/file. – Dennis Jun 25 '17 at 19:08
  • 4
    Possible duplicate of [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – John Dvorak Jun 25 '17 at 19:09
  • Related, but not a duplicate: [Difference between variable declaration syntaxes in Javascript (including global variables)?](https://stackoverflow.com/q/4862193) – Makyen Jun 25 '17 at 19:22
  • 1
    Note: As has already been stated, it appears your real issue is that `content` is defined and used in a larger scope. We don't know this for sure, because you have not provided us with a compete [MCVE] which actually duplicates the problem. – Makyen Jun 25 '17 at 19:29

1 Answers1

0

This has already been said in the comments, but most likely, you have defined a global variable with the name "content". It's not possible to 'redefine' the variable in a function (then it's a local variable).

It's recommended that you change your local variable name when it has nothing to do with the global variable, because your function changes the global variable, which may break the code.

Sacha
  • 819
  • 9
  • 27