When should var be used in Javascript?

Asked

Viewed 9,431 times

89

I’m always in doubt in the projects I put var before giving a value to a variable or not because both work (I think). Can anyone explain why they use it or not? What convention or good practice to be followed?

It’s a silly question I think, but as I never studied Javascript I would like to know.

  • 6

    Not a silly question, on the contrary. In fact, considering how often we see "polluted" Javascript code with global statements of variables, it’s a very relevant question!

  • @Maniero what would be his criterion used to determine that this question did not get enough attention?

  • @Guilhermecostamilam My strictly personal. Whoever is giving the reward can do it anywhere. It’s not a requirement to have a reason to spend your reputation to highlight something you think you should.

  • @Maniero I just wondered, had already seen you offer rewards to reward an existing answer. I didn’t understand the reason of this, I thought I suddenly wanted some updated answer with const and let, but I wasn’t sure

  • @Guilhermecostamilam this is about the var very user not yet use.

  • Next for being 'var' when the code is compiled, it has read preference.. Var hi = 0; it will be interpreted first than, oi = 1;

Show 1 more comment

6 answers

65


It is always recommended to use the keyword var because it makes the variable local, otherwise it becomes global. This avoids conflicts, corrupted variable, makes the code less vulnerable to access via address bar.

javascript:count = 0, a code similar to this would reset the count of the rapishare at the time of downloading, but since it had a side server validation it does not let download the file in a short period

example of variable exposed: (I tested this on Chrome, firefox ended up changing the javascript policy a lot if I am not mistaken from version 25 so the example will not work)

This code was taken from a real website.

<html>
<head>
<script language="JavaScript">
    var xtx=20; // linha original
    function IniciaRegressivo() {
        if (xtx > 0) {
            document.getElementById('botao').innerHTML =
           '<div class="protetor-botao"><a>Aguarde '+ xtx +' segundos</a></div>';
            xtx = xtx - 1;
            setTimeout("IniciaRegressivo();", 1000);
        } else {
            document.getElementById('botao').innerHTML = 
            '<div class="protetor-botao">
            <a href="javascript:download();">Fazer Download</a></div>';
        }
    }
</script>
</head>

<body onload="IniciaRegressivo();">

<div name="botao" id="botao"></div>
</html>

In the browser address bar type this 'code' (type at least javascript: and then glue the rest)

javascript:xtx=0;IniciaRegressivo();

see the result.

Now modify the line:

<script language="JavaScript">
    var xtx=20; // linha original

for:

if(typeof(xtx) == "undefined"){
   xtx = 80; //variavel local da função IniciaRegressivo() certo?
}

of a Ctrl+F5 and test again.

  • Your answer was really very helpful to me! + 1

  • It seems to me also, that global variables in JS do not work in IE8...not that it makes a difference in my life...but...

33

The var is key to distinguishing local variables from global variables. Without it, all variables will be global - worse, they will be global implicit, since the code does not make clear the scope.

This is serious enough to be forbidden in the strict mode of language:

function teste() {
    "use strict";
    x = 10;
}
teste(); // ReferenceError

Always keep in mind that each function creates a new scope in Javascript. Therefore, variables different but with the same name can exist inside and outside the function.

Compare:

var x = 10;
function alteraGlobal() {
    x = 20;
}
alteraGlobal();
alert(x); // alerta 20

Versus:

var x = 10;
function alteraLocal() {
    var x = 20;  // este x é outro, local!
}
alteraLocal();
alert(x); // alerta 10

That’s the basics you need to understand about scope and var in Javascript. For the subtlety of using or not var to purposefully create a global variable, see reply from Anthony Accioly.

26

What the documentation says?

As defined by mozilla documentation:

The Scope of a variable declared with var is the enclosing Function or, for variables declared Outside a Function, the global Scope (which is bound to the global Object). Using var Outside a Function is optional; assigning a value to an undeclared variable implicitly declares it as a global variable (it is now a Property of the global Object). The Difference is that a declared variable is a non-configurable Property of the global Object while an undeclared is configurable.

In free translation:

The scope in which the variable var is declared with the var is defined from the encapsulation of the function in which it is declared or, for variables declared out of function, the overall scope (which is the "boundary" of the global object). Using var outside of a function is optional; assigning a value to an undeclared variable implicitly declares the variable to be global (becomes a property of the global object). The difference is that a declared variable is a nonconfigurable property of the global object, while an undeclared variable is configurable.

What is the influence of this?

The implications can be obtained from the example found in the same documentation link previously provided.

var a = 1;
b = 2;

delete this.a; // Lança um TypeError no "strict mode". Senão falha silenciosamente 
delete this.b;

console.log(a, b); //Lança um ReferenceError. Como a propriedade 'b' não existe no objeto global, b deixa de ser uma variável.

Therefore, it is recommended at all times use the var when declaring an internal variable to a function, since assigning a value without declaring the variable within a function, can usually cause errors and, for this reason, the Ecmascript 5 Strict mode throws an error.

18

I will make a transcription (with slight adaptations in italic) of an answer user’s kangax in SOE which, in my opinion, is the best reference on the subject we have (surpassing the answer accepted to the original question in SOE).


There is a difference between statements with or without the use of var.

var x = 1 declares the variable x in the current scope (also known as execution context). If the statement appears inside a function - a local variable is declared; if it appears in the global scope - a global variable is declared.

x = 1, on the other hand, it is only an assignment of ownership. The interpreter try to solve first x against the scope chain. If it finds x anywhere in the chain of scope, he makes an assignment; if he does not find x, only then he creates the property x in a global object (which is an object at the top level of a call string e. g., window).

Now, you realize that the command x = 1 does not declare a global variable, it creates a global property.

The difference between the two is subtle and can be confusing unless you understand that variable statements also create properties (only in a Variable Object [link with me]) and that every property in Javascript (well, Ecmascript) has certain flags describing their properties - Readonly, Dontenum and Dontdelete.

How variable declaration creates properties with the flag Dontdelete, the difference between var x = 1 and x = 1 (when executed in the global scope) is that the first - variable declaration - creates a non deleteable property, and the last not. As a consequence, properties created through this implicit assignment can be deleted from the global object, while the former - those created via variable declaration - cannot.

But that’s just theory and in practice there are even more differences between the two, due to several errors in implementations (with IE).

I hope it all makes sense : )

[Update 16/12/2010]

In ES5 (Ecmascript 5; the recently standardized fifth language edition) there is a so-called "strict mode" - an optional language mode that slightly alters the behavior of undeclared assignments. Within strict mode, the assignment of an undeclared identifier is considered a Referenceerror. The justification for this is to identify accidental assignments, preventing the creation of unwanted global properties. Some of the newer browsers have already started to support strict mode. See, for example, the compatibility table on the kangax blog.

Notes from me:

  • We already have ES6 in the oven, scheduled to become a standard in December 2014. I left the update note (dated 2010) only to explain the behavior in strict mode.
  • ES5 the notion of Variable Object was replaced by that of Lexical Environments (I am not brave enough to try to translate either of the two concepts by thinking of at least 3 different translations for each).
  • 2

    kangax has a blog post where he explains all this in even more detail: http://perfectionkills.com/understanding-delete/

10

I believe that the best response that I have seen so far and that it is quite simple this in the OS itself.

Transcription

If you are in the global scope then there is no difference.

If you’re in a role, var will create a local variable, the non-use of var make him look for the variable by the scopes on top of him until he reaches the global scope, only then, if he did not find the variable was to create it (in the global scope).

// Estas estão no escopo global
var foo = 1;
bar = 2;

function()
{
    var foo = 1; // Local
    bar = 2;     // Global

    // Execute uma função anonima
    (function()
    {
        var wibble = 1; // Local
        foo = 2; // Herda do escopo acima (criada na função)
        moo = 3; // Global
    }())
}

If you’re not doing an assignment then you need to use the var:

var x; // Declara x

Obs

All the answers above are correct, I just pointed out this, because it seems to me the simplest.

9

Javascript is a broad language because you can do almost all the things you want on a web page, just by creating functions and finding ways to do.

I can say that Javascript is not a safe language, because you can easily access most of the variables and functions, read and know how it works, just accessing the *.js file, included in the page.

My Thought: Some access modifiers have been created to use in Javascript due to needs, because Javascript does not "transport" to other places (pages), unless you use a session variable.

And about that, some known modifiers:

private
protected
public

I can tell you that I know that some javascript modifiers have some resemblance to them, which are:

Local:

var Variavel = 0;

Automatically, it is converted to an Integer(Integer) variable, because it is receiving an Integer(Integer) value, and also, this is a local variable because of the modifier var that declares this variable in a way that you cannot access its value unless you are within the same function that this variable was declared.

Example:

If you declare these functions this way, with standard modifiers:

function conflito(){
  i = 2;
  mudarI();
  alert(i);
}
function mudarI(){
  i = 0;
}

In this case, the i is the same variable for both functions.

So if you run conflito() , you will receive an alert that results 0.

BUT, IF YOU DECLARE i using the modifier var:

function conflito(){
  var i = 2;
  mudarI();
  alert(i);
}
function mudarI(){
  var i = 0;
}

In this case, you have two variables ​​i, because they are restricted to use only within their function, so if you run conflito(); now, you will receive an alert with value of 2.

Variable belonging to the Method:

this.Variable = "a";

This variable is automatically a String, because it is receiving a String value, you probably already know what this modifier does, but, I will try to explain with my point of view, that is, this variable is coming from Superclass ie, which can be called a class , or in other words, the class "parent".

An example:

function TClass()
{
  this.getVar = function()
  {
    try
    {
      return "test";
    }
    catch(err)
    {
      return false;
    }
  }
  this.alertVar = function()
  {
    try
    {
      alert(this.getVar());
    }
    catch(err)
    {
      alert('erro');
    }
  }
}
var $Class = new TClass();

As you can see above, I created a class TClass and some variables that contain functions within (javascript closure) and added the modifier to them. To make them linked to TClass and, as you see in the function alertVar(), run out alert(this.getVar()), it performs the function that is TClass in this context.

And this part:

var $Class = new TClass();

I’m creating the class as you probably already know, to have access to your methods, making it possible to run, to test:

$Class.alertVar();

Resulting an Alert containing "test", as you can see :

alert contendo teste

Note that you cannot access the methods TClass otherwise, you can only access it if you create the class instance and access it from it.

I hope you have understood the usability of this modifier.

Global Variables:

window.Variable = true;

Javascript automatically declares this variable as a Boolean, because it is receiving a boolean value. The modifier window, as it says itself, you can access it at the moment you are in the window(window), because Javascript variables when declared, they go to the DOM of the window, see what is DOM:

DOM(Document Object Model): DOM is a cross-platform that represents the way the HTML, XHTML, and XML markups (Markup’s) are organized by the browser you are using. In other words, if you access the DOM you can see each Property, all variables , or anything that is currently declared in the browser.

Unlike other variables , the window variables may have assigned another value and access the current value, no matter where you are accessing, within a function or not, within a *.js file or not.

Example of Global(window):

Perform in the event onLoad from a page a code declaring a window variable(window), or declaring using the same browser console:

window.Variable = true;

Then add a JS file that contains this function, or just declare by executing the code in the browser console:

function testGlobalVar(){
  if (Variable)
    alert("funciona!");
}

When you perform testGlobalVar() you will receive the alert, but it is only because you declared it as 'window()' otherwise it will not run.

Standard modifier for Javascript:

Variavel = 0.5;

This variable is automatically declared as Float because it is receiving a Float value. I don’t know if you already know, but javascript variables declared as usual (no modifiers), have a pattern modifier that makes the variable look similar to window variables , but you can’t access it from anywhere you are, but in most cases, you can access it, particularly, I don’t know all the cases you can’t access it, but I know you can’t when you uploaded a *.js file and was declared inside it. Only if you perform a function that declares it, so it goes to the DOM and after that try to access.

However, I see you want to know about the var in question, but I gave you a general explanation of all the modifiers I know (I believe they are all), for your knowledge get wider and you have a better understanding of the modifier in question.

I hope you understand what I’m saying .

Ah, and if you got confused when you saw a function within a variable, study Javascript Closures, you will understand after a while :).

  • 1

    Very good. This content added a lot to me!

  • I may be wrong, but Javascript only has a numeric type (Nunber), both for integer and decimal values, so, 1 ===1.0 is true

Browser other questions tagged

You are not signed in. Login or sign up in order to post.