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.
user[name]
is returningundefined
. Whyundefined
?user[age]
is returning nothing. Why is it not returningundefined
like in previous case? What am I missing here?