Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Function properties in JavaScript

Today I learned something new about JavaScript. i.e JavaScript functions can have properties which can be accessed from within the function scope.

This is because,

In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object.

You can add properties to a function using the dot notation like so.

function fn() {
    // This is function property

fn.prop = 'This is function property';

As you can tell, you can set a property to the function before calling it. The property can later be accessed within the function when you call it.

This can be useful in scenarios where you want to inject some dependency without changing the function definition.

Check this example.

function updateUser(name, age) {
    if (updateUser.isAllowed) {
        console.log('User updated successfully');

    console.log('Not allowed');

updateUser.isAllowed = true;
updateUser('Jemini', 30)

As you can see, we needed a way to check whether the user is allowed to do this update operation and using function properties, it becomes pretty easy to set the property called isAllowed on the function without even changing the function definition!

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I do and want me to continue doing the same, I'd like you consider leaving a tip. I'd highly appreciate that. Cheers!