1

In javascript I have found some variable declaration without the 'var' keyword for example -

<script type="text/javascript">
 userId  
</script>

Then I think javascript may be a dynamically typed language like - python.

But in some other place found some variable declaration with the keyword'var'like -

<script type="text/javascript">
     var accountNumber
</script>

Since I am new in Javascript it's somewhat confusing to me. What's the diffrence between these 2 declaration. Does the scope of these two declared variable remain same?

Thanks

proshantoS
  • 55
  • 1
  • 10
  • possible duplicate of [Declaring variables without var keyword](http://stackoverflow.com/questions/6888570/declaring-variables-without-var-keyword) – makeitmorehuman Feb 14 '15 at 13:44
  • possible duplicate of [What is the function of the var keyword and when to use it (or omit it)?](http://stackoverflow.com/questions/1470488/what-is-the-function-of-the-var-keyword-and-when-to-use-it-or-omit-it) – Qantas 94 Heavy Feb 14 '15 at 13:45
  • In the first snippet `userId` is an expression, not a declaration, and it causes a reference error, since `userId` hasn't been declared. You should add some real code you haven't understood. – Teemu Feb 14 '15 at 13:48

1 Answers1

2

A variable-declaration without the "var" keyword creates a variable in the global scope.

This can introduce errors, if you are not careful. I would always use the "var" keyword to declare variables. The only exception I see is the definition of a global variable within the lexical scope of another function.

And, your first fragment is not a variable declaration at all, it is an expression, that will throw an error, since userID is not defined.

Mathias Vonende
  • 1,400
  • 1
  • 18
  • 28