Why does JavaScript allow to use variables without declaring?

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 this intentional or is it a flaw? So can I just exit using variables without declaring, in Python style?

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

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

i = 'asdasd';

document.write(i);
Author: Maniero, 2016-12-13

3 answers

If it is intentional or is flawed there are controversies:) well, it can be said that it is intentional. Like all" good " Dynamic Language , in every sense, like a script language it should be, she should make it as easy as possible for the programmer to do quick things unceremoniously. So it was chosen not to demand the declaration.

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

In the example there is no explicit declaration, 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 poorly thought out, but I cannot state that. Even if it is useful to have something global it would be preferable to have an explicit statement that is like this. At least the pattern should be local.

To be good even 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.

 11
Author: Maniero, 2020-03-30 16:09:54

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

See:

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


call_me_baby();

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

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

When you make a declaration of a variable without the use of var, we could say that it is the equivalent of making the assignment directly on the object window.

See:

call_me_baby() {
    window.a = 1;
}

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

You can even use var in 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-declaration of i could cause collision problems names and misrepresentations.

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 at:

 9
Author: Wallace Maxters, 2017-04-13 12:59:38

The language is not perfect:) being able to make value assignments to undeclared variables is a flaw of the language that has weak typing. I say failure because it generates overwrites of variables without realizing it and generates errors that are difficult 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 declared. b is exported to the global scope, which is dangerous and can generate ugly bugs. c is generated by function, as parameter. In a way it is declared, but not explicitly. This generates code interpretation errors and should be avoided, as we may think that calling the function without passing a value as an argument is a bug.

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

How to avoid 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 adhered to, one of them the same one you speak in the question. That is: in strict mode giving 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);
 4
Author: Sergio, 2016-12-16 08:11:56