Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the name property a different value from what I set it to? [duplicate]

Tags:

javascript

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"
like image 475
Rookie Avatar asked Feb 07 '23 13:02

Rookie


2 Answers

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

like image 68
linguamachina Avatar answered Feb 11 '23 00:02

linguamachina


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.

like image 27
Ayan Avatar answered Feb 11 '23 00:02

Ayan