- Podcasts
- CyberSecurity Summary
- Functional JavaScript: Introducing Functional Programming with Underscore.js
Functional JavaScript: Introducing Functional Programming with Underscore.js
CyberSecurity Summary
- August 21, 2026
- 25 min
About this episodeA comprehensive guide to applying functional programming principles within the flexible, yet often problematic, JavaScript environment…
You can listen and download our episodes for free on more than 10 different platforms:
https://linktr.ee/cyber_security_summary
Get the Book now from Amazon:
https://www.amazon.com/dp/B00D624AQO?lv=shuf&channelId=500&plpRedirect=mhFallback&linkCode=ll2&tag=cvthunderx-20&linkId=1950b7dcc6b0682721d9c95bcc5dd058&language=en_US&ref_=as_li_ss_tl
Discover our free courses in tech and cybersecurity, Start learning today:
https://linktr.ee/cybercode_academy
Transcript
From the publisherThis transcript comes from the podcast’s own feed, shown as the publisher wrote it.
Functional JavaScript: Introducing Functional Programming with Underscore.js
You know why we spend so much time chasing obscure state bugs instead of actually building new features. We tend to think we are so neatly categorizing our systems into these rigid classes and objects, but those implicit connections between the objects, they eventually just create total architectural gridlock.
Is, and Focus uses the underscore dot js library to basically demonstrate a completely different mental model for handling that complexity we just talked about. Right, we are moving away from focusing on nouns, you know, the rigid objects and classes that hold state, and we're shifting our focus entirely to verbs, pure isolated.
I mean you can write imperative step by step state mutations. You can build these massive, prototype heavy object oriented webs You can even lean heavily into metaprogramming by manipulating the execution model itself with proxies and reflection. Yeah. But and this is the key. It also provides the foundational tools for functional programming right out of the box, specifically through how it treats functions.
So raw materials, which is your data, go in one end, and as they move down the configor belt, they are transformed by these discrete single purpose machines right the verbs exactly. And a huge constraint of this assembly line is immutability. So the original raw materials are never destroyed and they're never mutated in place. You are always producing a brand new version of the data at every single station on the line.
So let's look at how that actually changes the developer's day to day approach in the real world. Fogus introduces a really practical example early on with this parsiage function. Right, the goal is super simple. You take a user input string and you parse it into an integer. In a standard imperative approach, you might write a function that parses the string. Sure, but it also probably contains hard coded console dot log statements for debugging oh always yeah, or maybe direct DOM manipulations to show warning banners on the screen if the input is malformed.
Right, things like a fail function or worn function, and then the parsiage function just takes those verbs in as arguments. So if you want to change how the system logs data, you literally just inject a different worn function into the pipeline. The actual parsing logic is never ever touched.
But to build an entire system out of these isolated verbs, the language has to support them natively, right like this hinges entirely on JavaScript treating functions as first class. Yes, now, I know you listening are probably familiar with the concept of first class functions, but let's just look at the mechanical implications of it really quick. Because a function in JavaScript is literally just an object under the hood. It can be assigned to a variable, it can be stored in an array, or like we just saw, it can be passed as an argument.
Yeah, but if I just write a standard imperative for loop that mutates an array in place, I am mathematically utilizing way fewer CPU cycles and I'm allocating way less memory. So at scale, doesn't treating everything as this immutable assembly line of tiny functions just absolutely tank the application's performance.
And one of the main tools it uses to do this is called inline caching. So if V eight sees that a specific tiny function like say our isolated warn function from earlier. If it sees that function being called repeatedly with the same exact types of arguments, it will eventually just stop executing it as a separate function call.
Yeah, so the overhead of the function call, the context switching, pushing of popping variables from call stack, all of that is entirely eliminated. V eight essentially flattens your beautiful, modular functional code into this highly optimized, imperative machine code block under the hood.
Well yeah, and in fact, a massive forur loop that does like five different things and mutates variables of all different types can actually confuse the GI compiler. Oh really yeah. Vight relies heavily on what are called hidden classes, which are basically predictable object shapes to optimize property access. If your imperative loop is constantly altering the shape of your objects, you know, adding or deleting properties dynamically, vight will actually de optimize that block of code. It kicks it back down, exactly, It kicks it back down to slow, unoptimized execution. But by writing small, pure functions that always return predictable data shapes, you are actually feeding the V eight engine exactly what it needs to optimize your code to near native speeds.
Which drives beginners crazy. It sorts them lexicographically. It coerces everything to a string first, so negative one oh eight comes before negative six, because the character one comes before the character six in unicode. It's this bizarre historical artifact from JavaScript's early days, when it was mostly just dealing with string data from HTML forms, and so to get a mathematical sort, the API forces you to pass in a very specific comparator function.
It will completely fail if you just pass it less or equal. So Fogus writes a higher order function, which is a function that returns another function, and he calls it comparator. This comparator function takes any boolean predicate as its argument, and it returns a brand new function that maps the true false output into the negative one, zero or one format that the dot sort API demands.
It's exactly like a travel adapter. That's a good way to look at it, right, Like if I take my laptop to Europe, the wall socket, which is the dot sort API, it demands a specific three prong shape my laptop charger, which is my less equal predicate. It only has a two prong shape. I don't rewire my laptop charger to fit the European socket.
And by not rewiring the core logic, that lesser equal predicate remains completely pure and completely reusable. You can use it tomorrow inside a filter function or a su function, which actually do expect boolean returns. If you had buried that logic inside of bespoke comparator, it would be locked away forever and totally useless to the rest of your application. And that is really the essence of functional composition, right. You build complex behavior just by snapping the gether these tiny, generic, re usable verbs.
But let's look at the other side of the equation, because if our verbs are these tiny decoupled adapters, what happens to our nouns? I mean, the prevailing philosophy in most enterprise software is object oriented design, where the data and the methods that operate on that data are all bundled together into these massive classes. If we are decoupling all the verbs, do we just toss out the classes entirely.
Well, this is where Fogus introduces a concept called data thinking, and it aggressively challenges standard op doctrine. He actually quotes Alan Perlis, you know, one of the pioneers in computer science who famously said it is better to have one hundred functions operate on one data structure than ten functions on ten data structures.
And the fundamental problem with that approach is that you are basically inventing a brand new, highly specific micro language for every single entity in your entire Systemma. Well, a user class might have a dot get role method, but an invoice class has a dot calculatol method. If you want to write a utility function to format some data, it has to be custom tailored to understand the specific bespoke methods of the user class or the invoice class. Your logic becomes completely coupled to the arbitrary shape of that specific class.
He demonstrates this with this lame CSV parsing example. So imagine a simple data set of employees. They've got names, ages, and departments. A traditional OP approach would parse that CSV and instantiate like a table class, which then holds an array of row classes which are mapped to individual employees classes.
Right, It's exhausting. But Fogus bypasses all of it. He just parses the CSV directly into an array of plane JavaScript objects, and that's it. That's the entire data model, an array of objects. But okay, here is where I have a major issue with this data thinking concept. If you strip away all the classes, you are also stripping away all the structural guarantees in a large code base. If I pass an employee object into a function, the class definition guarantees that the employee has an email property, and it guarantees that the email is a string. Right if we just throw raw arrays of loose objects around the code base, aren't we basically just crossing our fingers and hoping the data is shaped correctly? Like how do you prevent the whole system from collapsing due to missing properties without the strict contracts of a class.
Think about when the data actually enters your application. Say you're parsing adjason payload from an API request or you're reading that CSV file from earlier. That is your boundary. So you write robust validation functions right there at the edge. If the data fails the schema check at the boundary, you reject it immediately. But once the data passes the boundary and enters your internal functional assembly line. You just trust it. You don't need heavy classes to babysit the data internally because you've already rigorously verified its shape at the door.
Oh I see, So you decouple the structural validation from the runtime behavior exactly. And once you do that, the real power of that Alan Perliss quote really clicks into place because your data is completely uniform. It's just planarrays and objects, which means every single generic function in your toolkit can operate on it.
Yeah, this part of the book is an absolute masterclass because he builds the suite of functions to manipulate the data as if it were an actual relational database. Like he writes a project function which maps directly to a seql select statement. You pass it your array of employee objects and an array of keys you want, like say name and department, and it just maps over the collection and returns a brand new array of objects containing only those specific keys.
But the mechanical brilliance here is the composability. The project function takes an array of objects as an argument, and it returns inn array of objects. The restrict function is the exact same thing. Because their inputs and outputs share the exact same primitive data structure. They just chain together flawlessly.
You can pass the result of restrict directly into project, and then the result of that directly into As you are executing highly complex relational queries against your data without a single custom class, without a heavy RM, and critically without ever mutating the original data set. It's just beautiful.
Right. And to address your earlier concern about memory overhead, because JavaScript passes objects by reference, returning a new array from restrict or project doesn't actually mean you are duplicating the actual object data in memory over and over. Oh really, Yeah, you are simply creating a new array that contains pointers to the existing objects. So the memory overhead is surprisingly minimal, But the architectural safety you gain by not mutating that original array is just massive.
Which perfectly transitions into the final core concept that focus tackles, which is the existential threat to all of this functional safety, the big one, Because if we have this pristine assembly line where data flows through isolated machines without ever being destroyed, what is the single biggest danger to that factory? Mutability, specifically mutability in the global scope.
And Fogus illustrates this with a terrifyingly simple example. A variable silently leaks to the global scope, so he writes a global variable lavin la vida global. Now, because it exists on the global object, it is fully accessible to every single function, every module, and every third party script running anywhere in that environment.
I drink your monad, and just like that, the state is overwritten instantly without any warning whatsoever. No, and because object oriented programming relies so heavily on internal state mutations, if your classes depend on any external context, they are highly highly susceptible to these invisible side effects. Yeah, when your application inevitably crashes because a booleon suddenly became a string, the stack trace isn't going to tell you who drank your milkshake. It will only tell you that the code failed three steps later when it tried to evaluate the string. It's the broken tooth on the mechanical pocket watch all over again.
And the functional programming heavily mitigates this exact problem through the principle of referential transparency. A pure function does not read from the global scope, and it absolutely does not write to the global scope. Its output is derived entirely and exclusively from the arguments passed explicitly into it. If a function needs configuration data, you have to pass that data in as an argument.
And when you apply that discipline across an entire code base, you just eliminate entire categories of bugs. The cognitive load required to understand the system drops dramatically because you don't have to keep this massive mental map of what else might be secretly modifying your variables.
It really highlights how focus is functional. JavaScript is so much less about learning the syntax of a specific library like Underscore and way more about adopting this defensive, scalable engineering mindset. For sure, we've explored how JavaScript's multi paradigm nature allows us to basically shift away from rigid oop structures. We unpacked how first class functions power those applicator techniques, and how modern jit can like vight, make these abstractions incredibly performant under the hood.
Exactly, Well, what if we apply data thinking to our teams. What if we stripped away the rigid hierarchies and viewed our organizations as functional assembly lines. The raw material is the project, The verbs are the specific skills of the individuals on the team completely regardless of their title.
Could we build more resilient, adaptable companies if we stopped obsessing over managing the state of our org charts and started focusing on building better pipelines for our people's skills to flow through. So next time you're stuck in a bureaucratic bottleneck, ask yourself, are we acting like a broken pocket watch or are we building an assembly line?
