JavaScript variable scoping compared to C

For the most part, JavaScript looks like a C-like language in syntax. Lines end (optionally) with semicolons, conditional expressions are in parentheses (e.g. if (a == 1)), and blocks are surrounded by braces. But there are some huge differences in both syntax and behavior. JavaScript is weakly typed, and its object oriented programming is prototype-based, much different from C++/Java. And for someone who understands how memory for C variables is allocated, JavaScript has a number of surprises in its variables and variable scoping.

  1. There's no block-level scoping, so declaring a var inside an if{} block is the same as it being declared at the top of the function.
  2. Variables can be declared in the middle of a function, not just as the first lines of a function (as in C). But actually your code will just be converted to where the variables that are declared later are declared at the top, but left undefined. Why does it matter? Even if you declare a local variable to override the same name of a global variable, if you use the variable before the line where you explicitly declare it, then it will reference the local and not global variable. This is called "variable hoisting". But only the declarations are "hoisted", not any setting of values.
  3. Variables can be declared with or without the var keyword. And of course JavaScript doesn't take a type in a variable declaration (e.g. int, char). If you use a variable without 'var' it is automatically a global variable.
  4. JavaScript will allow you to both declare a variable with some name and then a function with the same name. What happens next depends.... Just don't do it.
  5. Object-oriented languages like Java let you use keywords to specify "private" members. JavaScript doesn't.