0

I made a typo in my code but it somehow still works.

let stuffs = [];
function stuff(thing) {
  stuff[0] = thing; // should be stuffs[0] = thing;
}
stuff("item");

I expected to get an error but somehow it still works. You can even get "item" with stuff[0]. What is going on here? Should I use this?

3
  • 2
    Actually stuff refers to the function so its setting property of function. Use console.log(stuff) to understand better. Commented May 7, 2019 at 18:15
  • @MaheerAli consider making this into an answer...too late. Commented May 7, 2019 at 18:19
  • 1
    @ctt I have got the max rep I could today. I can't get more so don't want to answer. Commented May 7, 2019 at 18:20

1 Answer 1

3

In JavaScript almost everything that has a structure inherits from Object.

In JavaScript objects can have any property.

With this statements you can see that a function is an object actually, so you can set all the properties that you want to it, just like a simple {} (with small limitations, as functions have another set of properties that plain objects don't have).

With this snippet you can check that functions inherit from Object.

function myFunc() {
    // empty! :-)
}

console.log("Func inherits from Object:", myFunc instanceof Object);
console.log("Array inherits from Object:", [] instanceof Object);
console.log("Object inherits from Object:", {} instanceof Object);
console.log("constant string inherits from Object:", "test" instanceof Object);
console.log(" * constant string DON'T inherits from Object but...");
console.log("String constructor inherits from Object:", String instanceof Object);

Sign up to request clarification or add additional context in comments.

2 Comments

Setting property of primitive types also don't throw error even though the property didn't gets set.\
Didn't get set because primitive types don't inherit from Object, as you can see in the example. Don't throws an error because primitives are "property accessible", meaning that you can access length for strings, call functions and whatever you write next to a dot. Because they don't inherit from Object, then when you access a non-existant property then the value is not saved, because the only way to save random properties is to inherit from Object. If don't throws an error I guess that is because of specification. JavaScript is really relaxed, as you already know haha.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.