Here is my code
var a = this.innerHTML;
var b = 'blababibbaib';
if(a !== b)
{
c = a;
return this.innerHTML = b;
}
else
{
return this.innerHTML = c;
}
and with the var
var a = this.innerHTML;
var b = 'blababibbaib';
if(a !== b)
{
var c = a; // here with the var it makes c undefined :-(
return this.innerHTML = b;
}
else
{
return this.innerHTML = c;
}
The reason I was doing this is because I wanted a function for an onclick event that would change back and forth between the original and var b. Just for fun really.
But I don’t understand why when you add the var in front of the c variable it makes it undefined once you click through it. Will someone illuminate me?
I’m guessing it has something to do with variable scope when used in functions????
Thanks in advance 🙂
Edit:
Okay, I did this to declare it with var, but I’m still not sure why exactly.
Outside the function I added an if check for c before declaring it
if(!c) var c = '';
But like I said, I would still like to hear whats going on and why Thanks 🙂
Edit 2: Thanks everybody, reading about hoisting now.
I was getting confused I think, it seems even you don’t need to check for c either. Thought might matter…oh well. Thanks again
What is happening in the second example is equivalent to this:
Obviously
cis undefined here, since it is output only when it is not set. I suspect what you actually want is:You can see it here.
As far as the first snippet is concerned, it works because the value of
cis not local to the function, and persists after its invocation. When you assign or refer to a variable in a function body without declaring it using thevarkeyword, it automatically refers to a property ofwindowwith the same name. Consider the following:In the first snippet, you are changing the value of
window.ctothis.innerHTMLwhenever the HTML is not"blababibbaib". When the value is"blababibbaib", you are relying onwindow.cto reset the element’sinnerHTML.You might want to read up on hoisting in JS, as well as implicit globals.