-4

I need help understanding something that I'm learning. Some lines of my code set a variable, name, which holds a name for a user and is set when an element is clicked.

The problem I've discovered is even without clicking the element, a user may still access it in the console.

I thought something was wrong with my code but I found the same accessing it on another site; for instance, accessing the variable on facebook yields "_e_0MDe". Other sites yield empty strings, like "".

Why does this happen? Thank you.

james Oduro
  • 673
  • 1
  • 6
  • 22

2 Answers2

4

window.name is just part of the DOM API. Facebook must be setting it.

If you declare a variable in a bare script tag, its treated as part of window

<script>
  var name = 'foo';
  console.log(window.name); // "foo"
</script>

In order to prevent that use a function to create a new scope (or use let)

<script>
  (function() {
    var name = 'foo';
  })();
  console.log(window.name); // what ever it was before this function call
</script>
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
0

JavaScript, like many scripting languages, can be very loose in variable declarations and initializations. This allows for quick development, but also means you have to be aware of scoping.

What you may be seeing is a collision in the global scope. By default, browsers have a global object called, window. This object can be used anywhere, in any function that you declare.

When you don't initialize a variable in a block with one of the reserved words (var, let, function, class, import, const), the global scope may be used. For instance, the following are equivalent:

  • name = 'foo';
    window.name = 'foo';
    

To help avoid syntax mistakes, developers often include a magical phrase at the top of their code:

  • "use strict";
    

More information can be found on John Resig's strict mode site.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75