What is a Lambda in Javascript ?

Lambda in JavaScript ? Can anyone tell me an example of one and why we should use them.

1 Answer

Jim Hoskins
Jim Hoskins
Treehouse Guest Teacher

Lambda can have different meanings depending on who you're talking to or what you're talking about. In the context of JavaScript it usually refers to an anonymous function. That is a function that doesn't get named, but is usually used as a value passed to another function in order pass a behavior as a value.

Here's an example. The Array.prototype.sort() function sorts an array. You can pass a function to define how to sort. In this example we are sorting by the name property of the object. In this example the lambda is a function that will receive 2 parameters (the 2 items to compare for the sort) and it should return a numeric value (negative for a before b, 0 for equal, positive for a after b)

var names = [
  {name: "Jim Hoskins", id: 1},
  {name: "Guil Hernandez", id: 2},
  {name: "Ben Jakuben", id:3}

names.sort(function (a, b) {
  if ( < {
    return  -1;
  } else if ( > {
    return 1;
  } else {
    return 0;

Generally we refer to them as "anonymous functions" in JavaScript, but in this case lambda would be a synonym.

Thanks Jim. :) I got it.

Also, I wish to see more JavaScript tutorials like the Robot Javascript bonus video.