Using State

Combining if statements with variables that change over time so your program reacts and behaves differently as it runs.

Welcome back. So far, we've been using variables for things that have some meaning, someone's age, the time, a color. We've updated variables, but they've been relatively static things. However, one of the most common uses of variables in coding is to track our progress throughout a job. Imagine you're building a wall, something you'll do in a moment. In real life, you'd be aware of which layer of bricks you're building, the bottom one or the top one, one in the middle, and you'd be aware of which brick you need to lay down next, the third, the fourth, et cetera. We need the same in the digital world, too. Or imagine you're trying to create an automatic Space Invaders bot. It needs to know where it is from the left to the right on the screen. In programming, we call this state, shorthand for what state is this in.

State is helpful in terms of knowing what's going on, but where it becomes really useful is when we combine it with conditionals. If we're building the wall, we need to check after each brick to see if we've laid down the last brick on that row, and if so, we need to move on to the next row and move back to laying the first brick. If we're building our Space Invaders bot, we need to check if we're at the edge of the screen before we move and reverse direction if we are, and that direction is state, too, a record of whether we're traveling left or right.

As you move forward, state is going to be one of the most crucial parts of programming, the idea of knowing where something is, what state it's in, or how far through our list of tasks we are. In these next two exercises, you're going to use state to build a wall and to play Space Invaders using the ideas we just discussed. It's really important to break these exercises down into little steps. Think through exactly what you need to know in order to solve them, things like the layer of bricks that you're on or the position of the current brick. Think through the rules that you need the computer to follow to lay the whole wall out. This is real programming now. This is the sort of thing that we do day in, day out as programmers. It's getting more complex, but it's also getting more fun. These patterns take a bit of time to get used to at first, so take your time, have fun, and I'll see you back here shortly.

Ready to Start Your Coding Journey?

Join thousands of learners on Jiki. Practice coding exercises, get feedback from mentors, and level up your skills — it's free!

Sign Up For Free