0

I am learning Javascript object creation using the constructor method and I am unable to understand one small behavior of the constructor in one of the examples.

<html>
<body>
<h2>JavaScript Objects</h2>
<p id="demo"></p>
<script>
            function User(name,age){
                this.name=name;
                this.age=age;
            }
            var user = new User('Daniel',45);
            document.getElementById("demo").innerHTML = user[name];     // Return undefined
            document.getElementById("demo").innerHTML = user["name"];   // Return Daniel.
            document.getElementById("demo").innerHTML = user[age];      // Retutn nothing. Blank
            document.getElementById("demo").innerHTML = user["age"];    // Return 45
        </script>

</body>
</html>

I read that object properties can be accessed with either Dot operator or Bracket operator. And here bracket operator seems to be working fine. Now I am unable to understand two things here.

  1. user[name] is returning undefined. Why undefined?
  2. user[age] is returning nothing. Why is it not returning undefined like in previous case? What am I missing here?
matthias_h
  • 11,356
  • 9
  • 22
  • 40
New2Java
  • 273
  • 1
  • 4
  • 19
  • The idea of the bracket notation is, that there is a string, or any expression which can be evaluated to a string, in the brackets. – Teemu Apr 16 '20 at 11:40

4 Answers4

4

When you do

user[name]

This looks up the property stored in the name variable. For example, if you had

const name = 'foo';
const result = user[name];

This is equivalent to:

const result = user.foo;

because foo is stored in the name variable.

The same thing is happening with age.

In contrast, when you use quotes, the interpreter doesn't look up a variable name, it just uses the plain string:

const result = user['foo']

is equivalent to

const result = user.foo;

But, keep in mind: best to avoid using the name variable, because on the top level, it exists as window.name which must always be a string, which can result in weird bugs if you're not expecting it.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Hmm... "This looks up the property stored in the name variable" makes sense to me now and when I am trying to access it, it's giving me undefined. Then why don't I get undefined for age as well? why it is blank when I am doing user[age];? – New2Java Apr 16 '20 at 11:44
  • You don't have a variable named `age`, so it throws an error: `age is not defined`. In contrast, the `name` variable exists because of `window.name` (but it's usually the empty string) - so, in that case, it won't throw an error, but still won't give you what you're expecting. – CertainPerformance Apr 16 '20 at 11:46
  • Wow... Now i understand it. by the way what is this window.name? Is it inbuilt? Please tell me a little bit more about it. – New2Java Apr 16 '20 at 11:48
  • You can read about it here: https://developer.mozilla.org/en-US/docs/Web/API/Window/name – CertainPerformance Apr 16 '20 at 11:49
0

The problem is when you write user[name] (assuming the name is Daniel) you are essentially trying to access the value at the key of Daniel which is a valid key. If this case Daniel would be the value at the key of name. Try doing this.

document.getElementById("demo").innerHTML = user.name;     // Return undefined
document.getElementById("demo").innerHTML = user["name"];   // Return Daniel.
document.getElementById("demo").innerHTML = user.age;      // Return nothing. Blank
document.getElementById("demo").innerHTML = user["age"]; 

Use the .name rather than [name] to get the value at the key of name.

Matt Croak
  • 2,788
  • 2
  • 17
  • 35
0

when you do user[name] what you really are doing is passing a variable called name and since you don't have a variable called name declared you will get undefined.

when you are doing user["name"] what you are doing is telling that you want to access the key name inside of your object.

you can also do

user.name

it will return the same thing as user['name']

Cyrus Zei
  • 2,589
  • 1
  • 27
  • 37
  • why this same behavior is not happening with age retrieval as well? I have not defined age var also. – New2Java Apr 16 '20 at 11:46
  • the same thing applies to the age and any key you have in your object. The key's (name and age) are pointers inside of your object so that you can find you value by key instead of like an array where you can find you value by index – Cyrus Zei Apr 16 '20 at 11:49
-1

You did not defined any name and age variables, so user[name] and user[age] will be undefined.

You need defined variable var name = "name" and use user[name] as below

<html>
<body>
<h2>JavaScript Objects</h2>
<p id="demo"></p>
<script>
            function User(name,age){
                this.name=name;
                this.age=age;
            }
            var user = new User('Daniel',45);
            var name = "name";
            var age = "age";
            document.getElementById("demo").innerHTML = user[name];     // Return undefined
            document.getElementById("demo").innerHTML = user["name"];   // Return Daniel.
            document.getElementById("demo").innerHTML = user[age];      // Retutn nothing. Blank
            document.getElementById("demo").innerHTML = user["age"];    // Return 45
        </script>

</body>
</html>
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62