Why does JavaScript allow you to use variables without declaring?

6

I was testing the JSFiddle with the code below. In it I did not declare the variable i , but even so, I can use it normally.

Is this intentional or is it a failure? So, can I just quit using non-declared, Python-style variables?

I also realized that I can use the variable anywhere in the code, obviously this makes sense because as it is not declared, it has no scope. But is this "possibility" just to be able to create "global scope" variables?

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

i = 'asdasd';

document.write(i);
    
asked by anonymous 13.12.2016 / 16:36

3 answers

6

If it is intentional or it is flawed there are controversies :) Well, it can be said that it is intentional. Like all "good" dynamic language , in every way, like a

13.12.2016 / 16:47
2

The language is not perfect :) Being able to make value assignments to undeclared variables is a language flaw that has poor typing. I say failure because it generates variable overrides without giving account and it generates hard-to-find errors.

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 declared explicitly. b is exported to the global scope, which is dangerous and can generate ugly bugs. c is generated by the function, as a parameter. In a way it is stated, 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.

Since there is a lot of code that trusts this (wrong) behavior, it is not unconventional to change this behavior.

How to avoid this?

The best way to avoid this kind of problem is to use strict mode . . strict mode is a command that causes a code to run in a more controlled mode. It requires that some important rules be fulfilled, one of which is the same that you speak in the question. That is: 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);
    
16.12.2016 / 09:11