Problem declaring variable 'name' javascript

Question:

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, the difference (apparently) of the variables being 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 an 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>

Answer:

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

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

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 which global variables are "reserved" by javascript:

//window === this => true 
console.log(this);
Scroll to Top