Statement vs. Expression in Dart

One of the foundational elements of any programming language is the statement, which represents a unit of code that performs a specific action or task. Another key element is the expression, which is a unit of code that produces a value when evaluated….


This content originally appeared on Level Up Coding - Medium and was authored by Ali Ammar

One of the foundational elements of any programming language is the statement, which represents a unit of code that performs a specific action or task. Another key element is the expression, which is a unit of code that produces a value when evaluated. In this article, we will explore the difference between statements and expressions to solidify our understanding of programming fundamentals and the syntax of the Dart programming language.

Introduction

First, let’s agree that any code you write is either a statement or an expression. That’s right — any code, from a single word to a complete function or class, falls into one of these two categories.

Statement

A statement is any code that ends a line or block of code (with ; or }) and consists of multiple expressions, operations, and other statements. For example, the code below is a statement because it ends the line with ; and performs the task of declaring and assigning a value to a variable:

final x = 5;

Another example is an if statement, which ends a block of code with }:

if (x == 5) {
print("hi");
}

Inside the above `if` statement, there is another statement: print(“hi”);, which ends the line of code with ;.

Expressions

As seen above, every line or block of code is a statement. So, what is an expression? An expression is any code that has or returns a value. For example:

final x = 5;

Here, 5 is an expression because it has a value. Let’s look at another example:

if (x == 5) {
print("hi");
}

In this code, we have six expressions and two statements:
- x is an expression because it has a value in memory.
- 5 is an expression.
- x == 5 is also an expression because it returns a boolean value.
- ”hi” is an expression.
- The call to the print function is also an expression because any function call returns a value (in our case void).
- print itself is an expression.

The complete line print(“hi”); is a statement because it ends with ; ,The if statement is also a statement.

To simplify, anything we can save inside a variable is an expression:

final x = print("hi");

The above code is valid because the call to the print function (or any other function) is an expression.

Consider this example:

final y = if (x == 5) {
print("hi");
}

The above code is incorrect because if is not an expression.

// Correct code
final hii = (String x, String b) {
print(x);
print(b);
return x;
};
// Incorrect code
final x = String hii2(String x, String b) {
print(x);
print(b);
return x;
};

The first function is correct because it uses a function expression (a function without a name). The second is incorrect because it is a function statement (has a name).

Expression Locations

In the above examples, there are places that must be filled with expressions to make the code correct. For instance, in an `if` condition, we must provide a boolean expression inside the parentheses to make the code valid. After the = sign is also an expression location, as are inside switch cases, when passing parameters to functions, and more.

Common Pitfalls

1. Using if statements as expressions to assign values:

const x = 5;
// Incorrect, `if` is a statement and cannot be assigned to a variable
final y = if (x == 5) 'hi';
// Correct
final String? y;
if (x == 5)
y = 'hi';
// Correct
final y2 = (x == 5) ? 'hi' : null;

2. Using if statements to pass parameters:

const secure = true;
// Incorrect
print(if (secure) 'secure' else 'insecure');
// Correct
print(secure ? 'secure' : 'insecure');

3. Returning or assigning a switch value:

const grade = 'A';
// Incorrect, as we try to assign a switch statement to a variable
final numberGrade = switch (grade) {
case 'A' => return 100;
case 'B' => return 90;
case 'C' => return 80;
case 'D' => return 70;
};
// Correct using a switch statement and assign later
final int numberGrade2;
switch (grade) {
case 'A':
numberGrade2 = 100;
case 'B':
numberGrade2 = 90;
break;
case 'C':
numberGrade2 = 80;
break;
case 'D':
numberGrade2 = 70;
default:
numberGrade2 = 60;
}
// Correct using a switch expression and direct assignment
final numberGrade3 = switch (grade) {
'A' => 100,
'B' => 90,
'C' => 80,
'D' => 70,
_ => 60,
};

4. Function expressions , function statements:

// Correct code (function as expression should be without a name)
final hii = (String x, String b) {
print(x);
print(b);
return x;
};
// Incorrect code (function with name is a statement)
final x = String hii2(String x, String b) {
print(x);
print(b);
return x;
};

5. collection if and collection for:**

These are used only inside lists, maps, or sets. They act as if and for but without a semicolon and allow returning one expression (not a statement).

const y = 3;

final list = [
5,
4,
if (y == 3) 2,
if (y == 1) 1 else if (y == 2) 2 else 3,
for (int i = 0; i < 10; i++) i,
];

final map = {
'a': 1,
'b': 2,
if (y == 3) 'c': 3,
if (y == 1) 'd': 1 else if (y == 2) 'e': 2 else 'f': 3,
for (int i = 0; i < 10; i++) i: '1',
};

final set = {
1,
2,
if (y == 3) 3,
if (y == 1) 1 else if (y == 2) 2 else 3,
for (int i = 0; i < 10; i++) i,
};

6. Arrow functions must return an expression

// Incorrect: using a statement in an arrow function
var multiply = (a, b) => {return a * b}; // Error
// Correct: using an expression in an arrow function
var multiply = (a, b) => a * b;

Trick

If you find yourself in a situation where you need to use multiple statements to calculate a value and pass it as a parameter or save it inside a variable, but you don’t want to write it above and save it first, you can define an expression function and call it directly inside the expression:

const a = 1;
const b = 2;
final x = () {
if (a == 1) return 1;
if (b == 2) return 2;
return a + b;
}();
print(x); // 1
print(() {
if (a == 1) return 1;
if (b == 2) return 2;
return a + b;
}()); // 1

Conclusion

Understanding the distinction between statements and expressions is crucial for mastering Dart or any programming language. Statements perform actions and usually terminate with a semicolon or brace, while expressions evaluate to a value and can be used wherever values are expected. Recognizing and properly using these constructs will help you write more effective and correct code, avoiding common pitfalls and leveraging Dart’s powerful features. Keep practicing and experimenting with different scenarios to deepen your understanding of these fundamental concepts.


Statement vs. Expression in Dart was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Ali Ammar


Print Share Comment Cite Upload Translate Updates
APA

Ali Ammar | Sciencx (2024-06-27T13:06:55+00:00) Statement vs. Expression in Dart. Retrieved from https://www.scien.cx/2024/06/27/statement-vs-expression-in-dart/

MLA
" » Statement vs. Expression in Dart." Ali Ammar | Sciencx - Thursday June 27, 2024, https://www.scien.cx/2024/06/27/statement-vs-expression-in-dart/
HARVARD
Ali Ammar | Sciencx Thursday June 27, 2024 » Statement vs. Expression in Dart., viewed ,<https://www.scien.cx/2024/06/27/statement-vs-expression-in-dart/>
VANCOUVER
Ali Ammar | Sciencx - » Statement vs. Expression in Dart. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/06/27/statement-vs-expression-in-dart/
CHICAGO
" » Statement vs. Expression in Dart." Ali Ammar | Sciencx - Accessed . https://www.scien.cx/2024/06/27/statement-vs-expression-in-dart/
IEEE
" » Statement vs. Expression in Dart." Ali Ammar | Sciencx [Online]. Available: https://www.scien.cx/2024/06/27/statement-vs-expression-in-dart/. [Accessed: ]
rf:citation
» Statement vs. Expression in Dart | Ali Ammar | Sciencx | https://www.scien.cx/2024/06/27/statement-vs-expression-in-dart/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.