Shorthand Syntax Expression | Fat Arrow Notation | Arrow Functions

Shorthand Syntax Expression | Fat Arrow Notation | Arrow Functions

ยท

1 min read

  1. Shorthand Syntax Expression (Shortened Way of Writing): Dart also supports shorthand syntax expressions, making your code more compact and readable. One common example is the null-aware operator (??), which provides a concise way to assign a default value if a variable is null.

    Example:

     // Long way
     String name = getName();
     if (name == null) {
         name = 'Guest';
     }
    
     // Shorthand way using null-aware operator
     String name = getName() ?? 'Guest';
    
  2. Fat Arrow Notation (=>): Fat arrow notation in Dart is a succinct way to define short functions. It's especially handy for one-liners.

    Example:

     // Traditional function
     int multiply(int a, int b) {
         return a * b;
     }
    
     // Arrow function
     int multiply(int a, int b) => a * b;
    
  3. Arrow Functions: In Dart, arrow functions are similar to fat arrow notation. They are concise ways to write functions, especially when the function body is a single expression.

    Example:

     // Traditional function
     String greet(String name) {
         return 'Hello, $name!';
     }
    
     // Arrow function
     String greet(String name) => 'Hello, $name!';
    

In Dart, these features enhance code readability and reduce boilerplate, making your codebase more elegant. Whether you're using shorthand syntax expressions or leveraging the simplicity of arrow functions, Dart provides concise ways to express your logic effectively.

ย