Problem in javascript variable declaration

Asked

Viewed 95 times

3

Can anyone explain to me what the problem is 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 only 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>

already when I place the code inside an IIFE the result will be 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>
  • 4

    name is a reserved Javascript variable. If you test on your console, you will see that it exists even without declaring it, I do not know the need for it. In the example below it works because you are declaring the variable name in an isolated scope, so it will only exist within your Function() {}block. Basically you will have a name that is in the scope above (in the case of the javascript reserved) and another name within the scope of the anonymous function that you created.

  • 3

    Wallace, post as answer :) Just not exactly a reserved word, is a global variable available in browsers (window.name).

1 answer

0

As already stated in the comments, name, as well as others, it is a variable that already exists in the object window of Javascript, therefore, the problem, however, when creating it in a different context, within a function, for example, this problem does not occur

Basically, to do var teste will be creating a variable in the context being executed, be it the window object or function, let teste and const teste declare the variable in the block scope if declared only teste the variable will be declared in the window scope, 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 what are the global variables "reserved" by javascript:

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

Browser other questions tagged

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