0

I always put var keyword before every variable. I'm wondering about it's correctness. Code is working, but is this good practice?

$(document).ready(function() {
    var something = 34;
    var v = $(body).find('p.lol');
    $.ajax({
        success: function(a) {
           var k = a.sdf;
           something = k+0.7;
           ...etc...
PiKey
  • 628
  • 5
  • 24

5 Answers5

3

Actually, it is not about coding practice. If you define a variable in a function using var keyword. it defined locally otherwise, the variable will be defined globally which you can access outside of the function.

function test(){
 var message = “hi”; //local variable
 variable = "bye";
}
 test();
 alert(message); //undefined
 alert(variable);//bye
sathish
  • 76
  • 8
1

Use var to define local variables. If omitted the variable will be global or you might accidentally overwrite the value of another variable.

Here's a similar question.

Community
  • 1
  • 1
Matt Zeunert
  • 16,075
  • 6
  • 52
  • 78
1

It's a good practice to always declare your variables (to avoid accidentally polluting the global object), but JavaScript has something called hoisting.

Basically, it means variables are always scoped to functions (i.e. not inside a loop or other statement block like other languages), so it's a good practice to do all your declarations at the start of each function.

Bennor McCarthy
  • 11,415
  • 1
  • 49
  • 51
1

Yes. If you use it in strict mode, will throw an error. Try it:

(function(){
    "use strict";
    try{
        myNum = 0;
    }
    catch(e) {
        alert("Error: " + e);
    }
})();

This code will return something like this:

Error: ReferenceError: assignment to undeclared variable myNum

More info:

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/Strict_mode

http://msdn.microsoft.com/en-us/library/ie/br230269%28v=vs.94%29.aspx

http://www.nczonline.net/blog/2012/03/13/its-time-to-start-using-javascript-strict-mode/

Erick Ribeiro
  • 756
  • 2
  • 8
  • 14
0

It is good practice in that you are clearly defining scope. When you do not use the var keyword you are effectively creating a global variable. Imagine that variable between automatically declared at the top of your file in that instance.

This creates local variables:

var someVarA = 23;
var someVarB = 25;

This creates global variables automatically (if not declared elsewhere):

someVarA = 23;
someVarB = 25;

This, however, is the same as placing a var in front of each variable (notice the comma):

var someVarA = 23,
    someVarB = 25;
scottc
  • 101
  • 2
  • 10