Skip to content

Where to declare javascript variables

I’ve been reading the new edition of Flanagan’s “Javascript: The Definitive Guide”, straight through, and I thought I’d make some posts about what I’d learned.

In javascript, variables are implicitly declared at the beginning of the function where they are used. So, in the following block,

global = 'global'; 
function f() {
   var global = "local";

The first console.log will log ‘undefined’ instead of ‘global’ even though the local variable named global has not been defined, because the javascript intepreter knows that a local variable named global will be defined within the scope of function f and implicitly declares it at the top of that scope. Good programming practice as I had understood it is that you should declare variables as close to where they are used as possible, to narrow their scope as much as possible. With this realization, for javascript, variables should be declared at the top of their scope, to make the readable code match the scoping that the language is doing behind the scenes.

Post a Comment

Your email is never published nor shared. Required fields are marked *