I am starting on my journey to learn HTML, CSS and JavaScript. There is a code sample I’m using which confuses me. I’ve read that it’s a good practice to declare any variables with the “var” keyword. With this example, however, the segment does not work when you declare the first variable “content” with the ‘var’ keyword. It is a reference to a HTML DOM, and so is the second variable called “button”. Can anyone explain to me why this strange behaviour occurs where one DOM object is declared with a “var” and the other not?
function initiate()
{
content=document.getElementById('secContent');
var button = document.getElementById('send');
button.addEventListener('click', read,false);
}
Hi @PeanutNUT when you declare a variable with the ‘var’ keyword inside of a function the scope of that variable will be limited to the function itself and the variable won’t be available outside of it. However if you assign a value to content inside the function without the ‘var’ keyword then ‘content’ variable will be of global scope and accessible outside of those functions. Hope that helps…
When you assign a value to content without the var keyword, JavaScript looks at each parent scope for where that variable might have been defined. Only if it gets up to the global scope without finding that variable will it then use a global variable.