Function declaration, definition, and call in Javascript

  • Functions in JavaScript are an essential part of the language, providing a way to create reusable blocks of code that can be called from other parts of a program. There are three main steps to working with functions in JavaScript: function declaration, function definition, and function call.

Function Declaration

  • A function declaration is a statement that creates a new function with a given name. It is created using the function keyword, followed by the function name, a list of arguments enclosed in parentheses, and the function body enclosed in curly braces. This step defines the function and makes it available for use elsewhere in the program.

    function addNumbers(a, b) {
        return a + b;
    }

Function Definition

  • A function definition is the process of providing the implementation for a function. This is where you write the code that the function will execute when called. It is typically done by writing a block of code inside the function body.

    function addNumbers(a, b) {
        return a + b;
    }

  • In this example, the function definition is simply the return a + b; statement, which specifies that the function should return the sum of the two input numbers.

Function Call

  • A function call is the process of executing a function by passing arguments to it. It is done by using the function name followed by parentheses and the arguments to be passed, separated by commas. The function call triggers the execution of the code defined in the function definition.

    var result = addNumbers(5, 7);
    console.log(result); // Output: 12

  • In this example, the addNumbers function is called with the arguments 5 and 7, which results in the value 12 being returned and stored in the result variable. The console.log statement then prints the value of result to the console.
  • In conclusion, function declaration, function definition, and function call are the three essential steps involved in working with functions in JavaScript. By understanding these steps and how they relate to one another, you can create reusable blocks of code that can be called from other parts of your program, making your code more efficient and easier to maintain.

No comments:

Post a Comment

Primitive Types in TypeScript

In TypeScript, primitive types are the most basic data types, and they are the building blocks for handling data. They correspond to simple ...