Problem in declaration of variable 'name' javascript

3

Can anyone explain to me what is the problem with the word 'name' in JavaScript? see this code:

The result of the first code will say that the variable name is an object and that name is a string, and the difference (apparently) of the variables is just the naming.

<script>

        var name = ["Henrique"];
        var nome = ["Henrique"];

        document.write("Tipo da variável nome " + typeof(nome));
        document.write('</br>');
        document.write("Tipo da variável name " + typeof(name));

    </script>

When I put the code inside an IIFE, the result will be the object for both.

<script>
        (function(){
        var name = ["Henrique"];
        var nome = ["Henrique"];

        document.write("Tipo da variável nome " + typeof(nome));
        document.write('</br>');
        document.write("Tipo da variável name " + typeof(name));
        }());
    </script>
    
asked by anonymous 12.07.2018 / 05:07

1 answer

0

As already said in the comments, name , like others, is a variable that already exists in the window object of JavaScript, so the problem is, however, when creating it in a different context, within a function, for example, this problem does not occur

Basically, to var teste is creating a variable in the context that is running, be it the window object or function, let teste , and const teste declare the variable in the block scope if it is declared only teste the variable will be declared in the scope of window, regardless of where the code is executed:

var teste1 = 'teste1';
let teste2 = 'teste2';
const teste3 = 'teste3';

!function(){
  let teste4 = 'teste4';
  teste5 = 'teste5';
}()

console.log(window.teste1); //teste1
console.log(window.teste2); //undefined
console.log(window.teste3); //undefined
console.log(window.teste4); //undefined
console.log(window.teste5); //teste5

If you want to know the global variables "reserved" by javascript:

//window === this => true 
console.log(this);
    
13.07.2018 / 03:08