I am currently reading a book on Javascript by Pragmatic, and I\'m confused about one thing. They have a section on how to make variables global, local, or private.
What is the difference between local and private variables? Is there one?
Depends in which context they are used. Generally they mean the same thing. From the OOP perspective, a local variables is usually called private.
How does one make a variable global or local, They said something about putting 'var =' before it, but it was very vague.
When you put var before variable, it becomes local variables, in the absence though, it becomes global variable. For example:
var foo = 1; // local
foo = 1; // global equivalent to window.foo = 1 becomes part of window object
More Practical Example:
function myfunc(){
var foo = 1; // presence of var keyword
bar = 2; // absence of var keyword
}
alert(foo); // error eg undefined
alert(bar); // 2 because bar is part of window global object