always one of those things in Python that I figured I’ll get around to understanding better one day soon! But the gist is that a lambda is a way of creating a function expression without a
so you can reuse a function in simple one-line or so expressions. They are intended to be handy little tools, as I understand it. They were not intended to be used to replace
def statements. You don’t use a lambda
expression where you should declare a function using
def. It’s more like a tweezers than a crowbar or refrigerator dolly.
So How Do You Use a Lambda Expression in Python?
Once again W3 Schools has a good explanation.
A lambda expression doesn’t have to be anonymous:
name = lambda arguments : expression
Robin = lambda str : 'Holy ' + str + " Batman!"
So now you could say
Robin("television addiction") and you would get back,
Holy television addiction, Batman! So in this case, the lambda expression is a simple string concatenation. But you could do math or
substitution or plenty of other things too. But this is the basic idea. It’s a function one-liner that can also be anonymous.
If you wanted to sum the numbers passed to a function:
l = lambda *args : sum(args)
and now you could say
l(1,2,3,4) and you’d get
sum is a handy Array method in Python. We would have to use
Mind you, there are many more ways than this to use lambda expressions in Python. But I’ll stop here for now.
I’m using a terminal with Node running in it for these examples just like I was running python3 in a terminal for the previous examples. Typing the following in a Node terminal:
let robin = str => "Holy "+str+", Batman!"
You’ll get the above mentioned effect in Node. If you enter
robin('television addiction') you will also get
Holy television addiction, Batman! just as in Python. Officially, I think you could call this a lambda
You could go:
const sumit = (total, num) => total + num
and then you could say:
arguments variable and the ‘rest’ variable
(...args), so I wonder what we could do with that?
const sumit = (...args) => args.reduce((x,y) => x+y )
Now, if we call
sumit(1,2,3,4) we get the right answer.
So, is this a lambda function in JS? Hmmm… I think maybe it is!
Conclusion: JS Lambda Expressions Like Python
Well, I’m just beginning my exploration of lambda expressions in JS, so I’m not concluding anything. But I now feel like there’s more to this than I thought at the beginning of this article. It’s taken me a couple of hours of struggling at the command line and the input of smarter people than I in my Slack channels to get to this point.