0

The difference between these two lines of code?

a = 'abc'; 

var b = 'abc';

Are they just different variables? is that it?

I want to say it is but I am just learning.

zubi
  • 13
  • 1
  • You should check it https://stackoverflow.com/questions/1470488/what-is-the-purpose-of-the-var-keyword-and-when-to-use-it-or-omit-it – Thai Doan Jul 10 '17 at 21:57

2 Answers2

3

The first one implicitly creates a global variable and the second one creates a variable in the current scope.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • Thank you! This would also apply to const correct? since Const replaced Var? and why would one be better than the other? – zubi Jul 10 '17 at 22:00
  • No, `const` did not replace `var`. `const` is a different way of declaring a variable as a "constant", once it's set the value can't be changed. – Scott Marcus Jul 10 '17 at 22:01
  • The value of a const can be changed, but the reference cannot. example `const a = { b: 'c' }; a.d = 'f';` is completely fine, whereas `a = 2;` will throw an arrow (because you are changing its reference) – enzoborgfrantz Jul 10 '17 at 22:14
1

It depends.

On global scope wise there is no difference. However, if you are on local scope there is a difference.

//Both global
var test1=1;
test2=2;

function first()
{
    var test1 =-1; // Local: set a new variable independent of the global test1
    test2 =3;     // Change the test2 global variable to 2
    console.log(test1); //will display -1 (local variable value)
}
function second()
{
   console.log(test1); //will display 1 (global variable value)
}

Inside function first() the value of test1 is -1 because we test1 is hitting the local variable created using var, function second() has no test1 as a local variable so it will display 1.

Oussama Ben Ghorbel
  • 2,132
  • 4
  • 17
  • 34