0

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 ?

Atif Imam
  • 83
  • 3
  • 10
  • 3
    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) – Manoj Salvi May 04 '16 at 08:28

2 Answers2

2

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

August Lilleaas
  • 54,010
  • 13
  • 102
  • 111
  • and if suppose a variable is defined inside a function without writing var before it , then it will be local variable . Am I right ? – Atif Imam May 04 '16 at 08:28
  • No - if you don't use var when declaring it, it becomes a global variable no matter where you declare it. – August Lilleaas May 04 '16 at 08:29
1
  • 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
steppefox
  • 1,784
  • 2
  • 14
  • 19
  • would you please explain your third point , with an example ? – Atif Imam May 04 '16 at 08:33
  • In JS you can write your code in `strict mode`. It helps you to avoid many strange things and strange behavior of your code. To enable strict mode, you just need to write `"use strict";` in the first line of your JS file (or function, if you want to enable strict mode only in one function). You can read more about it here https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Strict_mode – steppefox May 04 '16 at 08:39
  • So, when you have strict mode enabled in your code, and you trying to use variable without declaration, it will cause error. For example: `"use strict"; a = 5; // Exception` – steppefox May 04 '16 at 08:40
  • Glad to help ^__^ Just always use `var` and you will be ok ;D Also, in ES6 (ES2015, it's a new standard of JavaScript), instead of `var` you will be able to use `const` and `let`, but do not think about it now. Find some good book about JS, complete it first, and after that read about ES6. – steppefox May 04 '16 at 08:45