Pig and Cat
Pig and Cat

Reputation: 150

Why does function variable can have object property and number variable not?

I found very mysterious thing when I am using variable.

Please see below snippet.

var abc = function(){};
abc.prop = 1;

console.log(abc);
console.log(abc.prop);

var abc = 3;
abc.prop = 1;

console.log(abc);
console.log(abc.prop);

Question1: Why does using abc.prop not outputing assertion error even if they are not object?

Question2: if variable's type is function, it's property can be defined and if variable's type is number, it's property cannot be defined. why does it happen?

Upvotes: 1

Views: 218

Answers (3)

ibrahim mahrir
ibrahim mahrir

Reputation: 31712

According to MDN:

Data types:

The latest ECMAScript standard defines seven data types:

  • Six data types that are primitives:
    • Boolean
    • Null
    • Undefined
    • Number
    • String
    • Symbol (new in ECMAScript 6)
  • and Object

The primitive values do not inherit from Object so you can't assign properties to them.

The primitive values are copied instead of passed around using a reference to them.

You can assign properties to numbers, if the numbers are instances of Number:

var abc = new Number(55);   // abc inherits from Object via the Number class
abc.prop = 1;               // so this is valid

console.log(abc);
console.log(abc.prop);

Note: The console log of abc is wrong because SO's console.log logs abc as an object where it should log it as a number. Use the browser console instead. (abc indeed is an object as it inherits from Object via the class Number, but it should be logged as a number since it is an instance of Number).

Upvotes: 1

Why console.log(abc); of the first snippet is showing only the function body, without the prop property?

Because that's what console.log() is defined to do: "If it's a function, just display its body."

How can I get Function object's properties?

You can use

  • Object.getOwnPropertyNames(abc) for all properties' names,
  • Object.keys(abc) for the enumerable properties' names,
  • Object.values(abc) for the enumerable properties' values,
  • Object.entries(abc) for both enumerable properties' names and values.

like any other Objects.

Upvotes: 2

MorganIsBatman
MorganIsBatman

Reputation: 1010

In JavaScript, functions are first-class objects, so are treated as such. Since in your first snippet you have declared the variable abc to be of type 'function', it can have properties, just like any other js object. In the second snippet you have declared it to be of type number, which does not allow you to declare properties.

See this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions

Upvotes: 1

Related Questions