-1

I'm coming from AS3 to HTML5 javascript so this is kinda confusing:

1.

I noticed that inside objects, you do not need to declare vars:

var player = { 
type:'player',
x:50,
}

The same thing with vars (var type, var x) display errors, why is that?

2 . Why don't I need to declare a var in a function:

createPlayer = function(){
a = 5;
console.log(a); //works
}

3. I assume that inside a function, once you create a new var like this:

 var a; //global var
 createPlayer = function(){
 a = 3;
 }

it first searches to see if there's a global var called a, if it already exists it changes it's value, if not it creates it locally in the function. is that correct?

  1. Generally, when do I need to declare a var, and when not?

Thank you for your time.

RunningFromShia
  • 590
  • 6
  • 20
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var – epascarello Oct 03 '15 at 21:19
  • Just NEVER assigned a variable without declaring it first using `var` and then you will never be confused about what scope it is defined in. if you don't declare a variable with `var`, it becomes a global variable and this is considered a very bad practice and, in fact, will actually be an error in strict mode. – jfriend00 Oct 03 '15 at 21:21
  • 1
    Duplicate? [What is the function of the var keyword and when to use it (or omit it)?](http://stackoverflow.com/q/1470488/218196) – Felix Kling Oct 03 '15 at 21:25

2 Answers2

4
  1. Because variables and properties are different things.

    When you declare variable, use var. When you set properties in an object literal, don't.

  2. You don't have to use var in non-strict mode, but it's not recommended because the variable will become global. And not using var throws in strict mode.

  3. When you set some value to a variable, it's searched in the scope chain, and modified there. If the variable is not found anywhere, it's an error in strict-mode, or assigned as a property of the global object in non-strict mode.

  4. Always declare your variables somewhere. And preferably, as locally as possible.

Community
  • 1
  • 1
Oriol
  • 274,082
  • 63
  • 437
  • 513
0

If you use the keyword var inside a function then it is considered as a local variable otherwise it is considered as a global variable attached to the window object, let me give you this example

function test(){
    var attr1 = "first attribute"; // this is a local variable 
    attr2 = "second attribute"; // this is a global variable, so you can acess it from outside that function, once you call it  
}

// call the test function 
test();
console.log(attr1); // we get undefined because we used the keyword var
console.log(attr2); // we  get the valeu "second attribute" because it is considered as a global variable 

I hope this helps

ismnoiet
  • 4,129
  • 24
  • 30