KrIsHnA KrIsHnA - 2 months ago 13
Javascript Question

name already defined in console!?

Could anyone explain why this code returns


in firebug console?

Don't down-vote thinking it's just a typo! :O
I was curious to know why it doesn't throw an error!!!

function mds() {
var {
= {
namex: 'NAME',
score: '10',
className: 'Oop'
this.test = function () {
return name;
var x = new mds();

I would also love to hear more details on this type of variable mapping (or a link) ?


I would like to know why name is predefined with value "" in console?


The JavaScript part of the explanation here is simple.

When you do this:

  this.test = function () {
    return name;

It will first look for a variable named name in the scope of the function this.test(). When name is not found there, it will check in the parent function's scope as well. And since name is not defined there as well, it will look in the global scope, which is window, and returns the value of, which in this case is an empty string. This ( is what you are seeing when you run name in the console (or Firebug). This much is simple.

The value of is decided according to it's definition in the HTML Standard (not according to ECMAScript rules). This MDN page says: - Gets/sets the name of the window.

And in your case, the name of the window is empty, hence the empty string you are getting. That's the simpler explanation of why is empty.

If you really want to understand why is empty here, you need to check out the HTML Specification for what it says about browsing contexts. It says that the value of will be the name of the current browsing context.

A browsing context is an environment in which Document objects are presented to the user. (from the spec)

For example, when you create a link in HTML using the below code, the target attribute specifies the target browsing context in which the page is to be opened.

<a href="page.html" target="TargetName">Click me</a>

See more examples in this JSBin.

Hope this was somewhat helpful. Read the HTML Spec to understand more about browsing contexts.