Atif Imam
Atif Imam

Reputation: 93

Is there any difference/advantage of using var before a variable name in javascript?

I am learning javascript . And I noted that the instructor was making variables in two ways . first was (for example):

var name ="Any string here";

and second method was simply writing the variable name without writing var first :

name="Any string here";

And the result was same . So , is there any difference between these two ?. Which one is better to use ?

Upvotes: 0

Views: 53

Answers (2)

steppefox
steppefox

Reputation: 1844

  • First of all, it is a bad practice to not write var before variable declaration.
  • Second problem is a global declaration of variable without var.
  • Third, in strict mode using variable without declaration will cause Exception

Upvotes: 1

August Lilleaas
August Lilleaas

Reputation: 54593

Leaving out var makes it a global variable, so if you have name multiple places in the code, they'll overwrite each other.

Upvotes: 2

Related Questions