Watch this episode for free — or access the full course as a Professional Subscriber. Learn more here
Programming in Dart: Fundamentals
Part 1: Fundamentals Challenge: Play with Logical Operators
— Flutter & Dart

Lesson Complete

Play Next Lesson

Challenge: Play with Logical Operators

This video was last updated on Apr 26 2022

Practice using logical operators on your own, through a series of hands-on challenges.


Okay, we’ve done a lot work covering logical operators. It’s time to put your knowledge to the test. In this episode, we have two challenges. We’ll start with the first one. First, I want you to define two variables. One should be called a constant myAge and set it to you age. The other should be a final called message that you’ll print out to the console.

Now if the myAge is greater or equal than thirteen or less then equal than eighteen, set the message to You are a teenager. Otherwise set the message to Not a teenager. Then print out the message. Pause the video and try it out.

How’d your challenge go? Let’s review it now. First, we’ll start by creating some variables. First, define your age and a message.

const myAge = 47;
String message;

Here we define myAge as well as a message. Remember, if we don’t set a value when we define a variable, we must provide the type, otherwise, Dart will set the type to be a dynamic. Now let’s define our logic.

if (myAge >= 13 && myAge <= 18) {
    message = 'You are a teenager';
} else {
    message = 'You are not a teenager';

We add the expression checking both ages using the and logical operator. Then we set the message. Now let’s print the message.


Now let’s run the dartpad, and you’ll see that I am definitely not a teenager.

Okay, so that was the first challenge. The second challenge is to write this code so that it sets the code using a ternary operator. That is, write it in one line. Pause the video now and give it a shot.

How’d that one go? Let’s do this now. Let’s create a new message.

const anotherMessage =

Next we add our expression.

const anotherMessage = (myAge >= 13 && myAge <= 18)

Now we set the result in the case that the expression turns out to be true.

const anotherMessage = (myAge >= 13 && myAge <= 18) ? 'You are a teenager'

Now let’s add a string for the false condition.

const anotherMessage = (myAge >= 13 && myAge <= 18) ? 'You are a teenager' : 'You are not a teenager';

Now let’s print it out.


And that’s it - if we run, we get the same result, except this time, we’ve written it on one line. Awesome job!