Why does Javascript allow using variables without declaring?

Asked

Viewed 935 times

11

I was doing a test on Jsfiddle, with the code below. In it I did not declare the variable i, but still, I can use it normally.

Is that intentional or is it a flaw? So, I can just go out using variables without declaring, in Python style?

I also realized that I can use the variable anywhere in the code, obviously, it makes sense because since it’s not declared, it has no scope. But this "possibility" is precisely so we can create variables of "global scope"?

for(i = 0; i < 10; i++){
    document.write(i + '<br>');
}

i = 'asdasd';

document.write(i);

3 answers

12


If it is intentional or is flawed there are controversies :) Well, it can be said to be intentional. Like every "good" dynamic language, in every way, as a language of script should be, it should make life as easy as possible for the programmer to do quick things without ceremony. So it was chosen not to require the statement.

If you do not declare the variable you will have scope global, which is not ideal, and will assume the best value you can.

In the example there is no explicit statement, but the variable does not cease to be declared automatically. It remains global and a value is assigned.

I see the criterion of being global more as an accident of something ill thought out, but I can’t say that. Even though it would be useful to have something global it would be preferable to have an explicit statement like that. At least the standard should be local.

To get better they created the let, after all JS no longer wants to be a language of script. I advise reading there to better understand about scopes in JS.

  • Important to have quoted about the let. I didn’t know. I believe it would be the most viable in the case of for.

  • If you can use it, it’s usually better, because the var is lame too.

10

When you stop using the var in a variable declaration, you are declaring it in the global context, independent of the scope in which you declared it.

Behold:

function call_me_baby() {
    a = 1;
    var b = 2;
}


call_me_baby();

console.log(typeof(a), typeof(b));

Note that the variable a was "sent" to the global scope. Already the variable b was limited to the scope of call_me_baby.

When you make a declaration of a variable without using the var, we could say it’s the equivalent of making the assignment directly on the object window.

Behold:

call_me_baby() {
    window.a = 1;
}

In the specific case of for, would happen the same thing if you didn’t use var to declare the variable. The variable i would be implicitly defined in the overall scope, regardless of the scope in which the for is invoked.

You can even use the var in the for in two ways:

 var i;

 for (i = 0; i < 10; i++) {}

Or

 for  (var i = 0; i < 10; i++) {}

It is important to note that the non-disclosure of i could cause collision problems of names and improper statements.

Another important note is that with the use of "use strict", the lack of var in the statement of i could generate an error.

(function () {
  "use strict";
  a = 1;
 })();

See more in:

5

The language is not perfect :) Being able to make value assignments to undeclared variables is a failure of the language that has weak typing. I say failure because it generates over-writing of variables without giving account and generates difficult errors to find.

Example:

(function(c) {
    console.log(a); // undefined
    try {
        console.log(b); // vai dar erro
    } catch (e) {
        console.log('Erro!'); // erro: ReferenceError: b is not defined
    }
    var a = 10;
    console.log(a); // 10
    b = 10;
    console.log(b); // 10
    console.log(c); // undefined
})();
console.log('No escopo global:')
console.log(typeof a, typeof b, typeof c); // b dá number!, as outras estão undefined

In this example above the variable b and c are not explicitly stated. b is exported to the global scope, which is dangerous and can generate ugly bugs. c is generated by the function, as parameter. In a certain way it is declared, but not explicitly. This causes errors in the interpretation of the code and should be avoided, because we can think that calling the function without passing a value as argument is bug.

Once there is a lot of code that relies on this (wrong) behavior it is not peaceful to change this behavior.

How to prevent this?

The best way to avoid these kinds of problems is to use the strict mode. The Strict mode is a command that makes a code run in more controlled mode. It requires that some important rules be followed, one of them the same one you speak in the question. That is: in Strict mode give values to undeclared variables gives error!

function normal() {
    a = 10;
}
normal();
console.log(typeof a); // number


function strict() {
    "use strict";
    b = 10; // o código pára aqui pois isto gera um erro
}
strict();
console.log(typeof b);

Browser other questions tagged

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