Functions as Elements

Photo by Joanna Kosinska on Unsplash

I recently had a coding challenge where I theorised that a concise solution could be found if functions could be treated as elements and packaged into lists / arrays or even dictionaries. Perhaps I came across an article discussing this feature — hence the intuition — but I never really had the chance to try it out before then.

Turns out that in both Python and JavaScript, functions could indeed be treated as elements and behave appropriately when we pass valid argument(s) to them.

Imagine we wanted to create a simple list of functions that returns the area or volume of the object . The index of the function-element represents the object’s dimension, and the single argument to be passed to it represents the length of a side of the object.

So in the example below in line 1, if we were looking for the volume of a cube with a side length of 2 units, the volume would be 8 cubic units as shown in line 5.

Dictionaries would also work, where instead of using the indices, we provide key as a name of the function-value. The dictionary area provides the area of a square or equilateral triangle, such that the latter could be found via the code on line 7 above.

Then I had another question. Could we simply use object-oriented syntax in such a case — i.e.class.method — which would have been natural given that is how functions are organised as methods for classes. In Python, certain libraries such as Pandas have made this common to the point that it just comes to mind, rightly or wrongly. Unfortunately, as the attribute error in line 13 onward shows, native Python does not support such syntax.

What Python couldn’t, could JavaScript? Besides, wasn’t there a saying, “Everything is an object in JavaScript”?

So I tried it out. And it works! Line 5 shows that you could compute the area of an equilateral triangle by using area.triangle instead of area[‘triangle’]. The fact that dictionaries are referred to as “objects” in JavaScript should have been a dead giveaway.

Another day of discoveries.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store