JavaScript Object can't display output

Need some help. Why the code below doesn’t display the output value?

error : TypeError: Cannot read property ‘name’ of undefined

<body>
  <h1>Create JavaScript Objects</h1>
   <p id="demo"></p>

<script>
    function detail(name, age, work){
        this.name = name;
	this.age = age;
	this.work = work;
}
var person = detail("Max", 31, "Programmer");

document.getElementById('demo').innerHTML = person.name + " of the age " + person.age + " works has a " + person.work;

</script>
</body>

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

The new operator is used to construct an object.

You’ve just called the function detail normally, so it doesn’t return anything, so there is no property called name because you haven’t created an object.

var person = detail("Max", 31, "Programmer");

person has the value undefined assigned to it, undefined.name is not a thing.

var person = new detail("Max", 31, "Programmer");

person has the object { name: "Max", age: 31, work: "Programmer" } assigned to it


Couple of things:

  • constructor functions should be capitalised (Detail not detail). This doesn’t make any difference to functionality: it’s just convention. But it makes it obvious that it’s a function that is to be used as a constructor.
  • using class eliminates the issue, because it won’t let you call the constructor without new:
    class Detail {
      constructor (name, age, work) {
        this.name = name;
        this.age = age;
        this.work = work;
      }
    }
    
    so
    var person = Detail("Max", 31, "Programmer"); // Error!
    var person = new Detail("Max", 31, "Programmer"); // no Error
    
var person = new Detail("Max", 31, "Programmer");

This worked. Thank you @DanCouper

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.