Introduction to lambda expression with JavaScript [Easy-to-understand explanation for beginners]

6 min
Introduction to lambda expression with JavaScript [Easy-to-understand explanation for beginners]

Over the past year, I have had the opportunity to work as a mentor for some beginer engineers. Everyone seems to have learned the basic JavaScript grammar in the training, but I often see they confused when they encounter a lambda expression in their work and say, “Well, what is this way of writing?”

Like those newcomers, this article is written for those who are confused when they first encounter a lambda expression like () => console.log. This time I will explain the lambda expression using JavaScript, but the same idea can be applied to other languages.

What you can do by reading this article

You will be able to read and write lambda expressions!

What is “Lambda expression”?

In JavaScript, you can put a function in a variable or pass it as an argument.

For example, like this.

// Example1: Assign a function to a variable and execute
// Message "Hello world!" is displayed on the console
let showMessage = function (msg) {
  console.log(msg)
}
showMessage('Hello world!')

// Example2: Pass a function as an argument
// After 1 second, the console will display "1 second has passed!"
setTimeout(function () {
    console.log('1 second has passed!')
}, 1000)

setTimeout appeared in Example2 is a function that executes the function received by the first argument after X milliseconds (X is the number received by the second argument). It is used when you want to delay the function call.

In the above example, we create an unnamed function like function (argument) {/ * some processing * /} and put it in a variable or pass it as an argument. Such an unnamed function is called an anonymous function.

And “Lambda expressions” is a concise way to write this anonymous function.

Basics of lambda expression

Then, we will see how to write a lambda expression by comparing it with how to write an anonymous function.

Let’s write a function that takes one number and returns twice that number in two different ways.

// anonymous function
function (num) {
  return num * 2
}

// lambda expression
(num) => {
  return num * 2
}

If you look side by side, it’s easy to see what kind of correspondence they have!

Anonymous functions are written as function (argument) {/ * some processing * /}, while lambda expressions are written as (argument) => {/ * some processing * /}.

Lambda expressions are sometimes called arrow functions because they are written using arrows.

As a result of using the lambda expression, the 8-character “function” is now a 2-character =>.

Engineers are a race that doesn’t like to repeat things that take time. “It’s a hassle to write the 8-character function every time! It’s too long! My hands get tired!” Such thoughts may have given birth to the Lambda expression.

Well, good news for those who think, “It’s not a big deal if you just reduce 6 characters.” The great point of lambda expression is from now on. If the conditions are met, it can be rewritten shorter and more concisely.

Conditions that allow you to write lambda expressions shorter

Case1: Function has only one argument

You can omit the () from lambda expression only if it has one argument.

// before
(num) => {
  return num * 2
}

// after
num => {
  return num * 2
}

Oh, two characters have been reduced again.

Note that you cannot omit the parentheses if there are no arguments or if there are two or more arguments.

// 0 arguments
() => {
  console.log('cannot omit parentheses!')
}

// 2 or more arguments
(a, b, c) => {
  return a + b + c
}

Case2: When there is one process

If your function has only one operation, you can omit the curly braces in the lambda expression.

// before
() => {
  console.log('Hello world!')
}

// after
() => console.log('Hello world!')

Oh, it’s shortened!

By the way, please note that the curly braces cannot be omitted when there are two or more lines. Here is an example for your reference.

// cannot omit curly braces because there are 2 lines
(a, b) => {
  let result = a + b
  console.log(result)
}

Case3: When processing is only a return statement

If the only processing is a return statement, you can omit the letter return in addition to the curly braces.

// before
(a, b) => {
  return a + b
}

// after
(a, b) => a + b

It’s much easier to write in lambda expression.

Reconfirm conditions that allow you to write lambda expressions shorter using Example

Now, as a review so far, let’s convert a function that receives one number and doubles it to a lambda expression in order.

// anonymous function
function (num) {
  return num * 2
}

// lambda expression (no omit)
(num) => {
  return num * 2
}

// omit () because there is only one argument
num => {
  return num * 2
}

// omit {} because there is only one processing
num => return num * 2

// omit letter 'return' because processing is only a return statement
num => num * 2

How is it? You could write it very short, isn’t it?

The final form num => num * 2 is an intuitive expression to realize what you want to achieve, “double the value received as an argument”.

Conclusion

In this article, I’ve tried to explain how to write a lambda expression. I hope that those who read it will be able to read and write the lambda expression by themselves.

However, many people may not yet realize the convenience of lambda expression just by reading this article.

The following articles are recommended for such people.

These are tutorials that will allow you to easily manipulate the elements of an array using lambda expressions.

By the end of the tutorial, you will be able to write cool array operations in one line using lambda expressions!

みどー

みどー

ITコンサル会社→フリーランスエンジニアの経歴を経て、現在はスタートアップ企業でエンジニアをしています。30代前半ながら本業では年収1000万円&フルリモートで仕事できる環境を手に入れたので、今後は自分自身のプロダクトを作って会社に依存せず生きていくことを目標に副業開発やブログ発信をしています。副業開発・ブログ運営・IT技術情報について発信していきます。

FOLLOW

カテゴリー:
タグ:
関連記事