-1

I am pretty new in JavaScript and I have the following doubt about how correctly declare variable.

So are there some differences between this variable declaration:

my_pkcoda = document.getElementById('pkcodaSelected').value;

(my_pkcoda variable is not declared before into the code. It is declared here for the first time and a value it is assigned to it)

and:

var my_pkcoda = document.getElementById('pkcodaSelected').value;

Or there are no differences?

AndreaNobili
  • 40,955
  • 107
  • 324
  • 596
  • 1
    The main difference is the scope the variable will live in: In the first example it probably will be the global scope, whereas in the second one it will live in the current function scope (which may be identical to the global scope, if you have not used any function). – Sirko May 28 '15 at 08:39
  • 1
    possible duplicate of [Declaring variables without var keyword](http://stackoverflow.com/questions/6888570/declaring-variables-without-var-keyword) – CodingIntrigue May 28 '15 at 08:39
  • 1
    You should have your response here : http://stackoverflow.com/questions/2485423/is-using-var-to-declare-variables-optional – lucasgehin May 28 '15 at 08:40
  • 1
    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 May 28 '15 at 08:40

1 Answers1

1

The correct way would be to declare the variable with var in the scope where you wish the variable to live.

JavaScript, in non-strict mode, will forgive you not using the varkeyword. However, it will search for a declaration of the variable up through the scope chain until it hits the global scope where the variable will be declared if not found.

myGlobal = 1; // Auto-declared in global scope
var myOtherGlobal = 2; // User-declared in global scope

function myGlobalFunc() {
    myLocallyInitedButGlobal = 3; // Auto-declared in global scope
    var myLocal = 4; // User-declared in local scope
}

console.log(myGlobal); // Output: 1
console.log(myOtherGlobal); // Output: 2
console.log(myLocallyInitedButGlobal); // Output: 3
console.log(myLocal); // Output: undefined

See this answer for a more detailed explanation https://stackoverflow.com/a/1470494/883303

Community
  • 1
  • 1
Frederik Krautwald
  • 1,782
  • 23
  • 32