Menu
Coddy logo textTech

Arrow Syntax

Part of the Fundamentals section of Coddy's Dart journey — lesson 70 of 94.

Arrow syntax (=>) is a shorthand for functions with a single expression in Dart.

Regular function:

int add(int a, int b) {
  return a + b;
}

void main() {
  print(add(5, 3));
}

Arrow syntax version:

int add(int a, int b) => a + b;

void main() {
  print(add(5, 3));
}

Works with void functions too:

void greet(String name) => print('Hello, $name!');

void main() {
  greet('Dart');
}
challenge icon

Challenge

Beginner

In this challenge, you'll practice using the arrow syntax (=>) in Dart. Arrow syntax provides a concise way to write simple functions that just return a value.

Complete the code below by converting the regular function multiplyByTwo into an arrow function. The function should take an integer parameter and return that number multiplied by 2.

Expected output:

Regular function result: 10
Arrow function result: 10

Cheat sheet

Arrow syntax (=>) is a shorthand for functions with a single expression in Dart.

Regular function:

int add(int a, int b) {
  return a + b;
}

Arrow syntax version:

int add(int a, int b) => a + b;

Works with void functions too:

void greet(String name) => print('Hello, $name!');

Try it yourself

void main() {
  // This is a regular function that multiplies a number by 2
  int multiplyByTwo(int number) {
    return number * 2;
  }
  
  // TODO: Convert the function above to an arrow function below
  // The arrow function should do the same thing (multiply by 2)
  int arrowMultiplyByTwo(int number) {
    // Replace this with arrow syntax
    return number * 2;
  }
  
  // Test both functions with the number 5
  int regularResult = multiplyByTwo(5);
  int arrowResult = arrowMultiplyByTwo(5);
  
  // Print the results
  print("Regular function result: $regularResult");
  print("Arrow function result: $arrowResult");
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals