Today in class I talked about how writing pseudo code is a good technique for solving code problems. It helps us to think algorithmically if we talk to ourselves (out loud, or silently) about the problem we are trying to solve.
Then we write out what we’re talking about. Just write out all the pieces, the parts, that will be used. Write out what must be done with the parts, how they will interact or work together.
My example: The problem to solve is getting JavaScript to play Rock, Paper, Scissors. By writing out the “ingredients” we need to work with in this problem, and how those ingredients interact with one another, we start to get a grip on what needs to be done:
Notice how I did not use any JavaScript terms, such as variable or let, if or else if, or arrays. Pseudo code is just plain, normal English.
Continuing with more pseudo code: I am not finished yet. Now I have to reason out the things the program must do. Again, I will use just plain English to do this.
I might have everything I need now. I will think about the game and how we play it with two people, using their hands in the normal way. Maybe I want to offer “best out of three.” If I do that, I will also need to keep score. That’s more work, more code. If I decide to do that, I will add it to my pseudo code.
Starting to write real JavaScript: We can copy the pseudo code into a file as JavaScript comments, and then write the real code directly into those comments. Here’s a live example to show what I mean.
My example isn’t finished — it doesn’t completely play Rock, Paper, Scissors yet. It does run without errors, though, and that’s another important point: We can use the pseudo code comments to write one little bit of the program at a time, test it, and after it works, move on to the next little bit.
You can see that I moved my pseudo code around in the live example. I changed the order. That’s normal. As I figured out bit by bit how to solve each step that’s needed, I moved some of the pseudo code lower down, because I haven’t solved those parts yet.
You can see that I have removed the original three lines of pseudo code about a tie. I did that because my JavaScript has already handled any kind of tie, in lines 23–25 above.
As I continue to solve this problem, to make the “game” actually work, I might continue moving and even rewriting my pseudo code. At the end, I might delete the pseudo code comment lines. But I might keep them, to remind me how I solved it all.
Using pseudo code is not only for beginners. Experienced pros use it too.
Image source: Public domain, from Publicdomainvectors.org