Google News
logo
Dart - Interview Questions
How is function expression different from function declaration in Dart?
In Dart, function expressions and function declarations are two different ways of defining functions. Here are the key differences between them:

1. Syntax :

   * Function Declaration : Function declarations have a named function identifier followed by parentheses for parameters and a function body enclosed in curly braces.
     void myFunction(int a, int b) {
       // Function body
     }​

   * Function Expression: Function expressions are anonymous functions that can be assigned to variables or passed as arguments to other functions. They use the `=>` syntax (known as the fat arrow notation) to define the function body.
     ```dart
     var myFunction = (int a, int b) => a + b;
     ```


2. Naming :

   * Function Declaration: Function declarations have a named identifier that can be used to refer to the function elsewhere in the code.

   * Function Expression: Function expressions are anonymous and do not have a named identifier. They are often assigned to variables and referenced through the variable name.


3. Usage :

   * Function Declaration: Function declarations are typically used when you want to define a named function that can be called multiple times from different parts of the code.

   * Function Expression: Function expressions are commonly used for creating one-time or short-lived functions, such as callbacks, event handlers, or functions that are only used locally within a specific context.
4. Lexical Scope :

   * Function Declaration: Function declarations are hoisted to the top of their scope, allowing them to be used before their actual definition in the code.
  
* Function Expression: Function expressions do not have hoisting behavior. They must be defined before they can be used.

Here's an example to illustrate the differences :
void main() {
  // Function Declaration
  int result = myFunction(3, 4);
  print(result); // Output: 7

  // Function Expression
  var myFunctionExpr = (int a, int b) => a * b;
  int exprResult = myFunctionExpr(3, 4);
  print(exprResult); // Output: 12
}

int myFunction(int a, int b) {
  return a + b;
}​

In the above example, we define a function `myFunction` using a function declaration, and another function `myFunctionExpr` using a function expression. We call both functions and observe the output.

The function declaration `myFunction` is defined before it is used, and it adds two numbers. The function expression `myFunctionExpr` is assigned to a variable and multiplies two numbers using the fat arrow notation.

Function declarations are useful for creating reusable named functions, while function expressions offer flexibility and conciseness, particularly when creating anonymous functions or functions with a short lifespan.
Advertisement