Day 8 of 30 of JavaScript

Shoyab khan - Aug 23 - - Dev Community

Introduction

Hi there, readers! 😊 I hope you’re doing great. In our last session, we explored functions and their usage in JavaScript. Today, we’ll be discussing arrow functions and function invocation. Let’s dive right in!

Arrow Functions

Arrow functions offer a more concise way to define functions in JavaScript, having been introduced in ECMAScript 2015. They simplify the syntax compared to traditional function expressions and come with several advantages.

Syntax:

const myFunction = (parameter1, parameter2) => {
    // code to be executed
};
Enter fullscreen mode Exit fullscreen mode

Benefits of Using Arrow Functions:

  1. Concise Syntax: Arrow functions provide a streamlined way to define functions.

  2. Implicit Return: If the function body contains only a single expression, you can omit the curly braces {} and the return keyword. The result of that expression will be returned automatically. This feature makes arrow functions particularly handy for short, one-liner functions.

For example:

   const add = (a, b) => a + b;
Enter fullscreen mode Exit fullscreen mode

There are even more benefits to using arrow functions, which we will discuss in future posts as we delve deeper into JavaScript.

Function Invocation

A function's code will execute when it is invoked, or called, in various ways:

  1. When an Event Occurs: For example, a function can be triggered when a user clicks a button.
   button.addEventListener('click', fun);
Enter fullscreen mode Exit fullscreen mode
  1. When Called from JavaScript Code: A function can be executed directly within your JavaScript code.
   fun(); // Calls the function
Enter fullscreen mode Exit fullscreen mode
  1. Automatically (Self-Invoked): Functions can also be invoked immediately after their definition. This pattern is known as an Immediately Invoked Function Expression (IIFE). The function is executed right away without needing to be called elsewhere in the code.
   (() => {
       // code to be executed
   })();
Enter fullscreen mode Exit fullscreen mode

Conclusion

That wraps up our discussion for today! I hope you found it informative. In our next post, we’ll explore arrays and their methods. Until then, stay connected, and don’t forget to follow for more updates! 😊

. . . . . . . . . . . . .
Terabox Video Player