4

I am new to JavaScript. Can someone explain why I'm getting an unexpected value when I access the name property of the person function?

var name = function() {
    console.log('name');
}

function person() {
    console.log('hello person');
}

person.name = "hello";

console.log(person.name); // logs "person"
Jordan Gray
  • 16,306
  • 3
  • 53
  • 69
Rookie
  • 59
  • 4

5 Answers5

4

Functions have a "name" property that defaults to the, erm, name of the function itself. It can be accessed but not written to, so your assignment to person.name is ignored.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Function/name

linguamachina
  • 5,785
  • 1
  • 22
  • 22
1

Function.name is a non-writable and non-enumerable property defined for functions. So even though you

person.name = "hello";

Its not getting over-written. It returns the function name.

Community
  • 1
  • 1
Ayan
  • 2,300
  • 1
  • 13
  • 28
1

If you check name property descriptor you will see that it's not writable:

function person() {
    console.log('hello person');
}

var descriptor = Object.getOwnPropertyDescriptor(person, 'name');

console.log(descriptor);

As you can see it has "writable": false, which means that you can't change name of the function.

dfsq
  • 191,768
  • 25
  • 236
  • 258
1

In JavaScript, you can define readonly(writable: false) properties. Hence, the name property is one of them. For futher you can check this link out.

Defining read-only properties in JavaScript

Define Property

Community
  • 1
  • 1
Ramazan Kürkan
  • 156
  • 1
  • 10
1

Check the defineProperty doc

It is possible to define a property which is non-enumerable and non-writable through assignment operator

writable

true if and only if the value associated with the property may be changed with an assignment operator.

and

enumerable

true if and only if this property shows up during enumeration of the properties on the corresponding object.

name is one such property of function object.

Writable no

Enumerable no

Configurable yes

gurvinder372
  • 66,980
  • 10
  • 72
  • 94