Search code examples
javascriptfunctionjavascript-objects

Why can't I set a JavaScript function's name property?


I am learning JavaScript and read that functions are like objects and can have properties set like this:

var person = function(){
}
person.name="John Smith"; //output ""
person.age=21; //output 21
person.profession="Web Developer"; //output "Web Developer"

Why is the name property blank?

Thanks


Solution

  • Because name is a non-standard, non-writable property of function objects. Function declarations and named function expressions are named, while you have an anonymous function expression whose name is "".

    You probably wanted a plain object:

    var person = {
        name: "John Smith",
        age: 21,
        profession: "Web Developer"
    };