DEV Community

loading...

JS: Functions inside Constants, When, How, and Why to use them

kailyons profile image KaiLikesLinux ・2 min read

As I have been working on my EMXI Pure JS Library, I have been putting Functions inside of constants. It's not a difficult thing to do, but I feel like they should be used more often. So how do you make one, how do you call one, and why are they so valuable?

Putting The Function inside the constant.

To make one of these, it's quite simple. You simply open your whatever.js file, open a constant, and throw in a function, just like this:

const myConstant = {
    myFunction: function(argument1, argument2){
        // Your code here
    }
}
Enter fullscreen mode Exit fullscreen mode

You then simply call it by:

myConstant.myFunction(1,2)
Enter fullscreen mode Exit fullscreen mode

When could this be useful?

Well if you are like me and making a library with multiple similar functions, this becomes your best friend. I really am not too sure when else this could be super useful, other than maybe making multiple functions under the same name. Let's say you need to have a function for the perimeter of the square and another function for the area of the square, this works well for that kind of stuff.

I mostly see this as a library-centric approach though. Let's take the area/perimeter of a square idea. In EMXI for example, the functions are area.square() and perimeter.square(). This could save time for users of a library, but when making an application its use is a lot more limited. You could just name your functions perimeterOfSquare() and areaOfSquare().

Every situation is different, but this is just a short little thing for you to know one more (small but important) feature in programming languages like JavaScript.

Discussion (3)

Collapse
darkwiiplayer profile image
DarkWiiPlayer

What you just described is namespacing. It's been a thing in software for decades and depending on the language not doing so can be anything from the norm to a reason to have rotten tomatoes thrown at you. Personally I'm on the side of "always namespace everything", but that's probably just my Lua bias.

Collapse
kailyons profile image
KaiLikesLinux Author

Oh cool, I am a little bit of a newb to programming still, but I love sharing what I learn. I knew people in my sphere of influence who did not know such things and thought I should share how to do it in JavaScript.

Collapse
darkwiiplayer profile image
DarkWiiPlayer

It's definitely not something I see often in the javascript world, which, I assume, is partly due to how its use slowly shifted from very small scripts to add simple interactivity to complete applications that run entirely in javascript.

Forem Open with the Forem app