Declaring variables without var keyword

Viewed 98620

At w3schools there is written:

If you declare a variable, without using "var", the variable always becomes GLOBAL.

Is it useful to declare global variable inside the function? I can imagine to declare some global variables in some event handler, but what is it good for? Better usage of RAM?

8 Answers

Declaring a variable inside of a function without the use of var, let, or const is no more useful inside the function than is declaring that variable with var, let, or const. And, as noted in previous answers to this question, function-local, implicit global declarations can be confusing and problematic outside the scope of the function where they were declared.

I'd like to speak to some subtleties that are missing from the w3schools quote, and from previous answers to this question.

First of all, if you never call the function that generates implicit globals, you won't generate any implicit globals. This is a subtle difference from the w3schools quote because it defies the "always" section of their statement.

function generateImplicitGlobals(){
  x = "x";
  window.y = "y";
}

// before calling the generateImplicitGlobals function, we can safely see that the x and y properties of the window object are both undefined:
console.log("before calling the generateImplicitGlobals function, properties x and y of the window object are: " + window.x + " and " + window.y);

// before calling the generateImplicitGlobals function, we can test for the existence of global variables x and y; note that we get errors instead of undefined for both.
try{
  console.log("before calling the generateImplicitGlobals function, x is: " + x);
}
catch(e){
  console.log("before calling the generateImplicitGlobals function, an attempt to reference some global variable x produces " + e);
}

try{
  console.log("before calling the generateImplicitGlobals function, y is: " + y);
}
catch(e){
  console.log("before calling the generateImplicitGlobals function, an attempt to reference the global variable b also produces " + e);
}
Admittedly, I am sure that w3schools is aware that the implicit global declaration inside a function isn't made before the function is called, but, for folks who are new to javascript, it may not be clear from the given information.

Regarding subtleties of previous answers, once the generateImplicitGlobals function has been called, we can see that attempts to access either the window.x property or the global variable x return the same values (and that the window.y property and the global y variable return the same values). These statements are true when called from inside or outside the generateImplicitGlobals function.

function generateImplicitGlobals(){
  x = "x";
  window.y = "y";
  console.log("inside the function, x and window.x are: " + x + " and " + window.x);
  console.log("inside the function, y and window.y are: " + y + " and " + window.y);
}

// now, call the generator, and see what happens locally and globally.
generateImplicitGlobals();
console.log("after calling the generateImplicitGlobals function, x, window.x, y, and window.y are: " + x + ", " + window.x + ", " + y + ", and " + window.y);

I would say that it might hurt your security and even stability of your code.

As was mentioned above, you might make a mistake by simply misspelling your variables and a solution is the keyword "use strict";
With this keyword declared it will throw you an error: Uncaught ReferenceError: foo is not defined.

It also refers to a secured code:
1. When writing a secured code, we do not want our variables to be accessed anywhere besides where they were actually declared. Do not declare global variables without the need.
2. Always read warnings carefully and resolve them. Use "use strict";, JSlint and other tools to see and resolve warning to make your code better.

For what it's, worth "variables" can be appended to the arguments list in a function.

If you assign a new value to an argument, it is doesn't affect the callers perpsective of that argument , (even with an object, the variable that points to the object itself is unique to the function. properties of that object can be modified, but replacing the object entirely has no impact on the original object).

Assigning a new value to a named argument replaces it temporarily for the current scope (and derived scopes).

There is no difference between an argument and a variable in that respect, from the interpreters point of view. even if the caller does not supply a value, an empty variable is implied for each unused argument

Also, you can create externally available "persistent" variables by simply assigning values to a named function - they are in fact objects themselves.this can even be done from inside the function.


  function noVars(a1,/*vars=*/v1,v2,v3) {
    if (noVars.lastA1===a1) return noVars.lastAnswer;

    noVars.lastA1=a1;

    v1=a1*a1;
    v2=v1*v1;
    v3=v2*v2*v2;

    noVars.lastAnswer = a1+v1+v2+v3;

    return noVars.lastAnswer;
  }

the main difference is these "persistent" values survive between each call, whilst values in var,let, arguments are "empty vessels" at the start of each call. arguments can be preset by the caller, otherwise they are "undefined".

this might be seen as abusing the agument system, i see it as using it in non-standard way. any changes to the javascript spec that stops this working, would also break the fact that passing a value to an function is always "by value", even with object (the fact that an object is itself a reference is irrelevant).

this will also work:


  var noVars = function (a1,/*vars=*/v1,v2,v3) {
    if (noVars.lastA1===a1) return noVars.lastAnswer;

    noVars.lastA1=a1;

    v1=a1*a1;
    v2=v1*v1;
    v3=v2*v2*v2;

    noVars.lastAnswer = a1+v1+v2+v3;

    return noVars.lastAnswer;
  };

Related