Lesson 4: Controlling Memory with Variables

Overview

This lesson gets into the basic mechanics of working with variables in programs. The lesson shows students how to create and assign values to variables and navigates through a series of common misconceptions about variables and how they work. Along the way, the lesson tries to build up the student’s mental model of how computers and programs work, which is essential for being able to reason about programs.

Purpose

Developing a good mental model for how variables work in computer programs is absolutely essential to long-term success as a programmer. However, because most students have had years’ worth of math classes before taking this course, there are two major misconceptions that early students often have about variables. We suggest that you try to avoid relating this material to mathematics at all. Some of the words and symbols are the same, but:

  • The = sign in programming is an instruction to store a value in memory, NOT a statement of equality.
  • “Variables” in computer programming are just named pieces of memory, NOT unknowns in an equation or symbols for undetermined values.

Thus, lines of code that assign values to variables and expressions that use variables are really instructions to retrieve and store values in memory. And those values change while the program executes. Being able to reason about what’s happening in consecutive lines of code like:

      a = a + b;

      b = a + b;

correlates highly with a person’s success in programming because you must have a good mental model for program execution and what the computer is doing.

Agenda

Getting Started

Activity

Wrap-up

Extended Learning

Objectives

Students will be able to:

  • Use variables in a program to store numeric values.
  • Store the value returned by a function (randomNumber, promptNum) in a variable for use in a program.
  • Debug problems related to variable re-assignment.
  • Write arithmetic expressions that involve variables.
  • Reason about multi-line segments of code in which variables are re-assigned multiple times.

Links

Heads Up! Please make a copy of any documents you plan to share with students.

For the Students

Vocabulary

  • Data Type - All values in a programming language have a "type" - such as a Number, Boolean, or String - that dictates how the computer will interpret it. For example 7+5 is interpreted differently from "7"+"5"
  • Expression - Any valid unit of code that resolves to a value.
  • Variable - A placeholder for a piece of information that can change.

Introduced Code

Teaching Guide

Getting Started

Recall patterns in making event-driven apps.

You are now pretty well acquainted with the basic mechanics of making event-driven apps. There is a pattern to writing these programs that you should be used to:

  • Add UI elements to the screen.
  • Give the UI elements meaningful IDs.
  • Add event handlers to those elements.

Motivate the need for variables in our programs to make them more useful.

Moving Forward

However there’s a whole bunch of things that we can’t do in our apps yet. The next step is to learn how to control the computer’s memory to remember things while the program is running.

Most apps keep track of some information that changes and updates as you use the app. For example, a simple game can keep track of your score and the number of lives you have left as you play.

Note that keeping track of data while a program is running is different from remembering things in the long term across multiple uses of the app, things like storing the all-time high score or remembering your user profile.

Most programs need to use memory for even basic processing tasks. App Lab already keeps track of a lot of things for you in memory without you doing anything, like the position and styling of elements on the screen, especially if they are moving around.

But you will want to write programs that keep track of data that’s not “built-into” the programming environment. These apps use and control the computer’s memory to do this, and learning how to use memory in programs is a powerful skill to have. Today we’ll start!

Activity

App Lab: Controlling Memory with Variables

Transition to Code Studio

Teaching Tip

The Variables concept video is embedded in one of the early levels in the lesson on Code Studio, but it’s recommended that you watch the video as a class so you can make transitional or motivating comments before sending students to work in Code Studio.

Transition:

The programming tasks in this lesson acquaint you with basics of working with variables and building up a mental model for how programs use and manage memory. To keep things simple, the output will mostly be simple text displayed to the app screen or debug console. In the next lesson we’ll apply what you learn to an app for a simple game.

Wrap-up

Foreshadow adding variables to apps.

Remarks

Now that you’ve had a fair amount of practice working with the basic mechanics of variables, and learning how to debug your own problems, you’re more than ready to start using variables in apps.

This lesson is subtly one of the most important for you as a programmer. Being able to answer questions like the last multiple choice question in the lesson on Code Studio means that you have a good mental model for how programs execute code and how machines work.

Some research has shown that being able to answer questions about simple variable re-assignment correlates highly with doing well in programming overall. So you’re on your way!

Extended Learning

Students can make their own program that prompts the user for some numeric values and then performs an action. The user input values could be used to print a calculation to the screen, or they could be used to control some part of a turtle drawing (such as the number of times to repeat an action).

View on Code Studio

Unit 5: Lesson 4 - Controlling Memory with Variables

Background

This lesson gets into the basic mechanics of controlling the computer's memory, by working with variables in programs.

To keep things simple we're going to focus on some bare-bones examples so you get the basic ideas behind creating and using variables. We'll primarily just be displaying text in the console rather than enhancing an app for now.

We all want to make cool apps, but having a good mental model before you get in too deep will allow you to go further and faster later on.

Understanding the typical pitfalls of learning variables for the first time, combined with establishing a good mental model, will make working with memory and variables in the future much easier.

Vocab

  • Variable: In JavaScript (and most programming languages) the most primitive type of memory you can use is called a variable. It's called a variable because it's a piece of memory in which you can change what's stored - its value can vary.
  • To create a chunk of memory to use in a program you use the var command.
  • To assign a value to a variable means to store a value in memory; you use the = operator.
  • Variable re-assignment typically means to change the value of a variable based on its current value.
  • Expression - Any valid unit of code that resolves to a single value. (Variables can be assigned values that are the result of an expression.)
  • Data Type - All values in a programming language have a "type" - such as a Number, Boolean, or String - that dictates how the computer will interpret it. For example 7+5 is interpreted differently from "7"+"5"

Lesson

  • Understand the power of variables.
  • Learn programming statements to create, initialize, and change the values stored in variables.
  • Learn how to prompt a user for numeric input.
  • Solve several small puzzles and challenges related to moving values around in memory.

Resources

  • Tutorial videos: Introduction to Variables Part 1 and Part 2

Continue

View on Code Studio

What's happening in this lesson and next

We are going to take the next two lessons to learn about how to work with variables and then incorporate them into our clicker game in order to keep score. Here's the breakdown:

This lesson:

  • Moving memory around: Get your hands dirty with some of the basic mechanics and properties of working with variables.

  • Basic mechanics: To keep things simple we're going to complete some bare-bones examples so you get the basic ideas behind creating and using memory through variables. We'll primarily just be displaying text in the console rather than enhancing an app for now.

  • Establishing a good "mental model" for working with variables: We all want to make cool apps, but having a good mental model before you get in too deep will allow you to go further and faster later on.

  • Getting past misconceptions: Understanding the typical pitfalls of learning variables for the first time, combined with establishing a good mental model will make working with memory and variables in the future much easier.

Next lesson:

  • Adding variables to our apps.
  • Understanding when and where and to create variables so you can use them the way you want.
  • Useful things you can do with variables in apps.
  • Making decisions based on variables.

The Basic Mechanics of Variables

Next section acquaints you with the bare-bones basic mechanics of using variables in programs, creating, assigning a value and displaying the value to the screen or console, so you can see what's going on.

You will:

  • Know how to create a variable and assign it a value.
  • Know how to display to the screen.
  • Debug common problems with creation and display.

Continue

View on Code Studio

Student Instructions

Variables Toolbox

Let's get started with the most basic example of using and controlling the computer's memory with variables. The toolbox has a couple of new commands for working with variables.

We've given you some starter code that does three things:

  1. Creates a variable called score
  2. Assigns the value 0 to score
  3. Displays the value of the score to the console (see hint below about quotes)

Do This:

You're going to add another variable, assign it a value, and then display it to the console. Use the starting code as a model for what you need to create now. Create a new variable by dragging out the var block. Change the name of the variable from the default x to lives (see animation at right). Set the value of lives to be 3. Add console.log messages to show the value of lives.

The output in the debug console should look like this:

Debugging Tip: Displaying values of variables [click to expand] NOTE: To print the value of a variable you should not use quotes. Notice the difference between these two statements:
console.log("score")
console.log(score)
It's subtle but important:
  • When console.log sees quotation marks it thinks you want to print out the literal characters in the quotes.
  • When console.log sees something without quotation marks it assumes you're trying to print a variable, and it goes to retrieve its value and displays that.
  • View on Code Studio

    Student Instructions

    Do This:

    We've given you some code with some errors in it. Look at the error messages and try to figure out the problem.

    • Run the program.
    • Locate and fix the error.

    When you get it right the output to the console should look like this:

    As a reminder, App Lab gives you hints about errors in two ways:

    • Hover your mouse over the yellow triangles or red squares next to line numbers in the code to see what they say.
    • As usual, the Debug Console will also tell you about any errors while your program is running.
    View on Code Studio

    Student Instructions

    Debugging Variables

    There is a simple command called write in the UI Controls toolbox that is a fast and easy way to display text in the app itself. The way you use it is very similar to console.log. Let's debug another problem only using write instead of console.log.

    You may have already run into this problem! But it's worth mentioning again. To display the value of a variable you should not use quotes. Notice the difference between these two statements - the comments next to each line explains the differences:

     write("score");  // will display the literal characters s-c-o-r-e
     write(score);    // will retrieve the value of score and display it
    

    Do This:

    To solve these problems you should only add or remove quotation marks. Run the starter code Locate and fix the problems

    GOAL: Make the app display what's shown at right by only adding or removing quotation marks from the code given.

    View on Code Studio

    Student Instructions

    Create and Assign At Once

    It's so common to want to create a variable and give it an initial value, that JavaScript has a shortcut that lets you create and assign with one line of code like this:

    You'll also see a new block in the toolbox for this (see right).

    Do This:

    We'll just quickly practice using this form of variable creation and assignment. The code you write will achieve the same thing as the previous level in fewer lines of code.

    • Create a variable called lives and assign it the value 3 using the new one-line version of this command. (See animation at right.)

    • Add console.log statements to display the value of lives just as before.

    • The output in the console should (again) look like this:

    View on Code Studio

    Student Instructions

    Give Text Mode a Try!

    The block-based mode of programming is useful for getting code into your app fast and error free. But sometimes those little tiny edits are a pain. Use text mode instead! Text mode is designed to make typing code fast and easy, and it also gives a lot of help to make your code error free.

    Let's re-create these variables again, but explore some features of text mode this time.

    Try Each of These 3 Things

    We've given you the first two lines of code in a program. Expand each box below and try what's suggested - each builds on the previous one, so you might want to go in order.

    1. Switch to text mode and try to type. [click to expand]

    Switch to text mode and type out a console.log statement to display the value of score.


    2. Drag blocks into text mode. [click to expand]

    If you don't want to type everything you can drag a block from the toolbox into text mode and it will show you the text version of it. Add code to create the lives variable and a console.log message.


    3. Check out code completion. [click to expand] When you type commands a tool tip pops up that tries to guess what you're trying to type. If you see what you want in the box, highlight it (you can use arrow keys) and then hit the tab key. It will auto-complete the code for you!

    View on Code Studio

    Controlling Memory - Other ways to store values

    Tip: Say "gets" instead of "equals"

    We know that the = sign, in a JavaScript statement like a = b, isn't a statement of mathematical equality. It's an instruction to move memory around. We'll talk about how to do mathematical equalities in JavaScript soon, but for now we'll just focus on the meaning of =.

    One tip is to read a statement like var score = 0 as: "The variable score gets the value 0" or maybe just "score gets 0" to be brief. Another example: a = b + 7 should be read as "a gets b plus 7"

    When you read the = sign as "gets", and say it out loud that way, you'll prevent confusing yourself, and other programmers will know what you're talking about.

    As we're about to see there are other ways to store values in variables besides just hard-coding single numbers. But in all cases, even when it's more complicated, using the word "gets" when you see a single = sign will help your mental model of what's happening.

    In the next several levels we're going to see how to:

    • Assign the result of an arithmetic expression.
    • Assign the value returned by randomNumber.
    • Assign a value given by the user through promptNum.

    Continue

    View on Code Studio

    Student Instructions

    Variables and Arithmetic Expressions

    A common thing to want to do is store the result of an arithmetic expression. The 4 basic arithmetic operations + - * / are available.

    Here is a quick table that shows the arithmetic operators with code examples [click to expand]
    operation block text example result
    add + result = 7 + 3; stores 10 in result
    subtract - value = 7 - 3; stores 4 in value
    multiply * score = 7 * 3; stores 21 in score
    divide bonus = 7 / 3; stores 2.3333 in bonus
    parentheses none () avg = (99 + 85 + 93) / 3; stores 92.3333 in avg

    Misconception Alert

    When you have a statement like result = 5 + 7; realize that this does NOT store a mathematical expression in the variable.

    Rather, with this instruction you are asking to compute 5 + 7 and THEN store the answer (a single number) in the variable.

    Do This:

    GOAL: the goal here is mostly to acquaint yourself with typing arithmetic expressions - the answers to the questions below are less important, and should be used as interesting things to investigate.

    We've given you some starting code with 5 statements similar to ones in the table above. Add console.log or write statements to display the values of each of the variables. Experiment with arithmetic expressions, try to make really big and really small numbers.


    Things to Try: Using multiplication: what's the biggest a number you can store in a variable? * How many digits are in the biggest number before it starts using scientific notation? Using subtraction (or multiplication with negative numbers): what's the lowest number you store? (low means a negative number with a lot of digits) * Using parentheses make a crazy-big arithmetic expression.
    * NOTE: composing arithmetic expressions is much easier in text mode, and is actually almost unreadable in block mode. Try doing this in text mode.

    View on Code Studio

    Student Instructions

    Text and Variables Living Together!

    Sometimes it’s useful to display text along with the value of a variable in the same line of output. To do this you use + to attach a variable onto a literal string of characters. Here is an example:

    Notice that the + operator has two different meanings in JavaScript depending on what type of data you're applying it to. Click the explanations below for more details.

    If both operands are numbers + means to add those two numbers together.

    This is standard addition. It works both with numbers and with variables that contain numbers, as shown below.


    Because num1 is a variable that holds a number, and 10 itself is obviously a number, in this case + will do addition like you would expect.


    If either of the operands is a string + treats both as if they were strings and combines them to create a single string. This is potentially confusing behavior and can get pretty weird if the text looks like numbers. For example, this code will display 16100 to the screen.


    Why? Because JavaScript sees you trying to display a mix of text and variable values. "16" (in quotes) is a string of ASCII characters not a number. And so JavaScript converts everything to text, and the characters in the result of "16"+"100" comes out to "16100".


    TIP: It's common to want to sandwich a variable between some text when displaying it. You can string together multiple pieces of text and variables using the + operator. For example, you can do this:



    Misconception Alert

    The key thing to understand about the + symbol is that it can only do actual arithmetic addition if the values on either side of the + are actually numbers or variables that contain numbers.

    And if the + symbol cannot determine whether the value is a number then it assumes it's a string, and converts everything to a string and tries to concatenate it.

    The computer relies on you - the programmer - to make sure that the type of data stored in a variable is appropriate for the task at hand.


    On the next screen we'll have you play with this a little bit, but you'll write statements to display a mix of text and strings from here on out.

    Do This:

    We have given you the starting code shown below. You should modify the write statement on line 3 to combine text and variables together to make the app display a single line of text as shown.

    starting code output
    View on Code Studio

    Student Instructions

    Expressions with Variables

    Arithmetic becomes much more interesting when we use other variables in our expressions. For example you can do this:

    Mental Model ![](https://images.code.org/b4a2c125508fb06fd653b90c643cb53b-image-1447272790306.png)

    The end result of an expression with variables is the same as one without. The major difference is that values are retrieved from memory in order to do the calculation rather than simply hard-coded.

    Mental Model Check

    Watch the animation above. To compute the expression the computer will: first retrieve each of the values of the variables used in the expression; then the arithmetic expression can be evaluated; finally the computed value can be stored in memory.

    Do This:

    * Scenario: In the starting code we have provided you with variables that might be the kinds of things you would keep track of in a game: totalTime, points and lives. (see right).

    • Right now the totalScore is just set to 0. We want you to compute a final score so that the person is rewarded for having a lot of points and lives, but penalized for taking a lot of time.

    • Write an expression that calculates the player's total score and stores it in the totalScore variable. The calculation is: the player's points times lives divided by the total time.

    • For the values provided the app display should look like this:

    View on Code Studio

    Student Instructions

    Other Ways to Assign Values to Variables

    Programs become much more interesting when the values in variables change while the program is running. We can also assign to a variable the value returned by a function. For example:

    Because the randomNumber function evaluates to a number it means we can treat it as though it were a number. We've used it before by just "plugging it in" to some function that needed a number as a parameter like:

    Because the randomNumber function generates a new and different number each time you call it, one thing we could not do before we had variables was generate a random number, and use that same number for two different things in a program. Now we can.

    Do This:

    Write a program that simulates the rolling of two dice and reports their individual values as well as the sum. The program should: Generate two random numbers between 1 and 6 and store each result in its own variable. Display the individual values of the two dice. Display the sum of the two dice (see right). Every time you run the program the result will be a little different.

    We have given you starting code that shows what to do for the first die. The rest of the code is up to you! When you're done the output in the app display should look like what's above.

    View on Code Studio

    Student Instructions

    Getting User Input - A Simple Calculator

    Programs become even more interesting when we can interact with the user. A short way to ask a user for a number is with the promptNum command, which pops up a dialog box asking the user to enter a number.

    This very simple app demonstrates a new behavior: getting input from the user. You will write code to re-create this program on the next page.

    Do This:

    • Click "Run" on the app.
    • You will be prompted for two numbers, one right after the other.
      • If you don't enter a number it will simply re-prompt you until you do.
    • See what happens.
    • Re-run the program and enter different numbers until you get the idea.

    Click Finish to move on.

    View on Code Studio

    Student Instructions

    Assigning User Input to Variables

    Let's use promptNum to make a simple calculator. The promptNum command appears in the variables toolbox because it's typically used as a way to get a value from the user that you want to hold on to while the program runs.

    promptNum is similar to randomNumber in that it is a function whose return value evaluates to a number. The difference here is that promptNum pops up an input dialog box and waits for the user to type a number. Once they do and hit "OK" the number they typed is returned and we can store it in a variable to use in our programs.

    Do This:

    Write a program that acts as a simple calculator. (An animation of the end result is shown at right.) Ask the user to enter a number. Then ask the user to enter a second number. Display the result of some* calculation. * The example shows division but you may choose something else if you like.

    We have given you starting code that shows you how to get the first number. The rest of the code is up to you.

    View on Code Studio

    Student Instructions

    Variable Reassignment - Part 1

    So far we have only set a variable's value once. But it's called a variable for a reason - its value can change (or vary) throughout a program. This is useful and necessary for keeping track of things like a score in a game.

    To re-assign a value to a variable all you have to do is maintain the mental model of what's happening:

    • Variables are containers for information.
    • The = sign is an instruction to set the value.
    • A series of assignment statements (see example to right) is a list of instructions to execute one at a time - it's not a series of equations that define the state of the world.

    Do This:

    • Make a prediction.

    The code on the following screen looks like what is shown at right. Study it and make a prediction about what will happen when you run the code. What will the values of a and b be at the end of the program?

    Prove it to yourself by adding console.log statements at the end of the program to find out what the value of a and b are.

    • NOTICE: in the code above, after the variable a has been created using var, to change a variable's value, you only need to refer to the variable by its name. The word var only needs to be used once - when the variable is created for the first time.

    • It's a common mistake to use var everytime you want to use a variable but just remember var means CREATE a new variable. When you create a new variable it will lose its old value. We'll look at errors related to this later.

    View on Code Studio

    Variables - The Mental Model

    A piece of code like the one to the left can cause confusion to early programmers (but not you!). Below we show you a technique you can use to trace out what's happening in memory as you mentally go through the code line by line. Even pros do this to verify for themselves that the code is doing what they think it will. This is also a form of making a prediction which really helps you see and learn what's happening faster.

    Here's what you do. You know that the code involves two variables (or two chunks of memory) so on a piece of paper make two boxes to represent the containers for values, then fill in the containers with values as you trace out each line of code.

    Code / Instruction State of Memory (write on paper)
    Before code is executed

    Create a variable called a that gets a value of 3.

    Label one of the containers a and write 3 in the box.

    Create a variable called b and it gets a value of 7.

    Copy the current value of b into a.

    Scratch out the old value in a - its value is being changed -- write in the new value.

    Copy the current value of a (which is now 7) into b.

    NOTE: the value of a changed on the last line! So you must use the value that's currently in a for this line. Also note that even though it's the same value (7) you're still instructing the computer to put a value into memory, and the computer will just follow whatever instructions you give.



    You'll get a chance to practice this technique in the next few challenges.

    Continue

    View on Code Studio

    Student Instructions

    Variable Re-assignment - Part 2: Updating Values

    All of our examples so far have shown how to set the value of a variable by using combinations of numbers and other variables. But what if you wanted to do something like add 10 to the current value of a variable?

    Because updating the value in a variable is just moving memory around, the process has to go something like this: Read the current value of a variable. Add 10 to it. * Store the new value back into the same variable.

    The technical term for this is called variable re-assignment - when you change the value of a variable based on its current contents. To increase the value of num1 by 10 you actually need to do this:

    num1 = num1 + 10;
    

    The diagram at right shows a picture of what's happening (it assumes the value of num1 is 7 before the line is executed). It's actually very similar to what happens with plain old arithmetic: compute a value, then store it in a variable. Because the computation has to happen before storing the result in a variable, there is no contradiction here.

    Common Mistakes & Tips [click to expand]

    Mistake 1

    To increase the value of variable by 10 (for example) a common mistake is to think that this statement alone will do the trick.

    wzxhzdk:1

    It doesn't. This tells the computer to add 10 to whatever the value of `num1` is. And the computer will do that, and the result will go....nowhere. It will be lost.

    Because you are trying assign a new value to a variable it should make sense that **the = sign must be involved somehow**.

    Mistake 2

    If you were in math class this statment would make no sense: wzxhzdk:2

    But **remember to read = as "gets."** If you read the statement above as: "num1 *gets* the value of num1's current value plus 10" it might make more sense. Get in the habit of using "gets."

    Do This:

    • Make a prediction. We start you out with some code again (see below).

    Trace the code and predict what you think will be printed to the console. (NOTE: We're serious about this "make a prediction" stuff. When you force yourself to make a prediction about what code will do you will learn faster since it triggers you to apply your mental model of what's happening.)

    • Run the program to see if you were right.

    • Add a console.log statement.

    We've left you with a little bit of programming to do: add a console.log statement at the end of the program to see the last value of someNum to see if your full prediction is correct.

    View on Code Studio

    Student Instructions

    Moving Memory - Challenge 1

    The next several levels all present challenges related to "moving memory" around in your program.

    GOAL: Set the value of the variable(s) to make the console.log statement display what it's supposed to.

    Rules:

    • You may only add lines of code that re-assign values of variables provided.
    • You may only use assignment (=) and arithmetic operators (+ - * ).
    • You MAY NOT type or introduce any numbers.
    • You MAY NOT add or create any new variables.
    • You MAY NOT change or alter the console.log statement at all.

    Example:

    Code Provided


    The code you're given will have a few variables initialized to some values. The last line will be one or more console.log statements with a comment indicating what the expected value to display should be.
    A Possible Solution


    You need to add a line (or multiple lines) of code to re-assign the values in variables so the console.log statement displays what's expected. In this example we show a solution on line 5. Please note that there are several different things you could do. For example, you could go crazy and do something like: y = x + x + (x/x);. What you do is up to you.


    Try this example yourself...

    View on Code Studio

    Student Instructions

    Moving Memory - Challenge 2

    Try another one!!

    • Click through to see a new problem provided in the starter code.
    • A reminder of the rules and example are below if you need to sneak a peek.

    Reminder of the rules (click to expand)

    **GOAL:** Set the value of the variable(s) to make the `console.log` statement display what it's supposed to.

    **Rules**:

  • You may **only** add lines of code that re-assign values of variables provided.
  • You may **only** use assignment (`=`) and arithmetic operators (`+` `-` `*` `/`).
  • You **MAY NOT** type or introduce any numbers.
  • You **MAY NOT** change or alter the `console.log` statement at all.

    Example:

    Code Provided


    The code you're given will have a few variables initialized to some values. The last line will be one or more `console.log` statements with a comment indicating what the expected value to display should be.
    A Possible Solution


    You need to add a line (or multiple lines) of code to re-assign the values in variables so the `console.log` statement displays what's expected. In this example we show a solution on line 5. Please note that there are several different things you could do. For example, you could go crazy and do something like: y = x + x + (x/x);. What you do is up to you.


  • ### Try it yourself...
    View on Code Studio

    Student Instructions

    Moving Memory - Challenge 3

    Try another one. Here is the starting code:

    var x = 2;
    var y = 3;
    // your code here
    
    console.log("The value of x is: " + x + " (x should be 7)");
    

    Reminder of the rules (click to expand)

    **GOAL:** Set the value of the variable(s) to make the `console.log` statement display what it's supposed to.

    **Rules**:

  • You may **only** add lines of code that re-assign values of variables provided.
  • You may **only** use assignment (`=`) and arithmetic operators (`+` `-` `*` `/`).
  • You **MAY NOT** type or introduce any numbers.
  • You **MAY NOT** change or alter the `console.log` statement at all.

    Example:

    Code Provided


    The code you're given will have a few variables initialized to some values. The last line will be one or more `console.log` statements with a comment indicating what the expected value to display should be.
    A Possible Solution


    You need to add a line (or multiple lines) of code to re-assign the values in variables so the `console.log` statement displays what's expected. In this example we show a solution on line 5. Please note that there are several different things you could do. For example, you could go crazy and do something like: y = x + x + (x/x);. What you do is up to you.


  • ### Try it yourself...
    View on Code Studio

    Student Instructions

    Moving Memory - Challenge 4

    Try another one. Here is the starting code:

    var x = 2;
    // your code here
    
    console.log("The value of x is: " + x + " (x should be 8)");
    

    Reminder of the rules (click to expand)

    **GOAL:** Set the value of the variable(s) to make the `console.log` statement display what it's supposed to.

    **Rules**:

  • You may **only** add lines of code that re-assign values of variables provided.
  • You may **only** use assignment (`=`) and arithmetic operators (`+` `-` `*` `/`).
  • You **MAY NOT** type or introduce any numbers.
  • You **MAY NOT** change or alter the `console.log` statement at all.

    Example:

    Code Provided


    The code you're given will have a few variables initialized to some values. The last line will be one or more `console.log` statements with a comment indicating what the expected value to display should be.
    A Possible Solution


    You need to add a line (or multiple lines) of code to re-assign the values in variables so the `console.log` statement displays what's expected. In this example we show a solution on line 5. Please note that there are several different things you could do. For example, you could go crazy and do something like: y = x + x + (x/x);. What you do is up to you.


  • ### Try it yourself...
    View on Code Studio

    Student Instructions

    Moving Memory - Challenge 5

    Try another one. Here is the starting code:

    var x = 2;
    var y = 3;
    var z = 0;
    // your code here
    
    console.log("The value of x is: " + x + " (x should be 3)");
    console.log("The value of y is: " + y + " (y should be 2)");
    

    HINT:(click to expand) Since this one requires you to change the value of two variables you need to be careful about which one you change first, since its new value will affect the next lines of code.

    You can also take advantage of the fact that since z is not used as a display value, you can use it as a temporary holding ground for one value while you change another.

    Reminder of the rules (click to expand)

    **GOAL:** Set the value of the variable(s) to make the `console.log` statement display what it's supposed to.

    **Rules**:

  • You may **only** add lines of code that re-assign values of variables provided.
  • You may **only** use assignment (`=`) and arithmetic operators (`+` `-` `*` `/`).
  • You **MAY NOT** type or introduce any numbers.
  • You **MAY NOT** change or alter the `console.log` statement at all.

    Example:

    Code Provided


    The code you're given will have a few variables initialized to some values. The last line will be one or more `console.log` statements with a comment indicating what the expected value to display should be.
    A Possible Solution


    You need to add a line (or multiple lines) of code to re-assign the values in variables so the `console.log` statement displays what's expected. In this example we show a solution on line 5. Please note that there are several different things you could do. For example, you could go crazy and do something like: y = x + x + (x/x);. What you do is up to you.


  • ### Try it yourself...
    View on Code Studio

    Student Instructions

    Moving Memory - Challenge 5

    Try another one. Here is the starting code:

    var x = 5;
    var y = 11;
    var z = 4;
    // your code here
    
    console.log("The value of x is: " + x + " (x should be 2)");
    console.log("The value of y is: " + y + " (y should be 6)");
    console.log("The value of z is: " + z + " (z should be 8)");
    

    HINT: (click to expand) This one requires you to be a little clever. Think about setting the value of one variable that you could then use to easily set the value of the other variables. Then the trick is to figure out how to use the variables you've been given to make that useful value.

    Reminder of the rules (click to expand)

    **GOAL:** Set the value of the variable(s) to make the `console.log` statement display what it's supposed to.

    **Rules**:

  • You may **only** add lines of code that re-assign values of variables provided.
  • You may **only** use assignment (`=`) and arithmetic operators (`+` `-` `*` `/`).
  • You **MAY NOT** type or introduce any numbers.
  • You **MAY NOT** change or alter the `console.log` statement at all.

    Example:

    Code Provided


    The code you're given will have a few variables initialized to some values. The last line will be one or more `console.log` statements with a comment indicating what the expected value to display should be.
    A Possible Solution


    You need to add a line (or multiple lines) of code to re-assign the values in variables so the `console.log` statement displays what's expected. In this example we show a solution on line 5. Please note that there are several different things you could do. For example, you could go crazy and do something like: y = x + x + (x/x);. What you do is up to you.


  • ### Try it yourself...
    View on Code Studio

    Student Instructions

    Wrapping Up Variables - This is Not Math Class

    Hopefully you now understand the gist of working with variables. The major thing to remember is that every time you see an = sign it means that you are instructing the computer to set a variable to a new value.

    The example to the right is something that definitely wouldn't make sense in math class, but you should be able to reason about it as a piece of code. Because it's code, you can also insert statements to display the value of variables as they change. You don't have to guess!

    Do This:

    • Make a prediction.

    As usual you should first look at the code given to you and reason about what it does. You should try to predict what the value of num will be after all lines have executed.

    Insert console.log statements into the existing code to display each value of num immediately after it's changed. (The animation below shows how to get started.)

    • Was your prediction right?

    After you figure out the answer, if your prediction was off, try to understand why. Where was your misunderstanding?

    View on Code Studio

    Student Instructions

    Can you figure out the values of a, b, and c?

    Using what you know about variables and re-assignment you should be able to trace this code and keep track of the values of a, b, and c as they change. You should also have a sense of any possible errors that could occur.

    Trace the code, and choose the option that correctly shows what will be displayed.

    Standards Alignment

    View full course alignment

    CSTA K-12 Computer Science Standards (2011)

    CPP - Computing Practice & Programming
    • CPP.L2:5 - Implement problem solutions using a programming language, including: looping behavior, conditional statements, logic, expressions, variables and functions.
    • CPP.L3A:3 - Use various debugging and testing methods to ensure program correctness (e.g., test cases, unit testing, white box, black box, integration testing)
    • CPP.L3A:4 - Apply analysis, design, and implementation techniques to solve problems (e.g., use one or more software lifecycle models).
    • CPP.L3A:5 - Use Application Program Interfaces (APIs) and libraries to facilitate programming solutions.
    CT - Computational Thinking
    • CT.L2:12 - Use abstraction to decompose a problem into sub problems.
    • CT.L3A:1 - Use predefined functions and parameters, classes and methods to divide a complex problem into simpler parts.
    • CT.L3A:3 - Explain how sequence, selection, iteration, and recursion are building blocks of algorithms.

    Computer Science Principles

    5.2 - People write programs to execute algorithms.
    5.2.1 - Explain how programs implement algorithms. [P3]
    • 5.2.1C - Program instructions may involve variables that are initialized and updated, read, and written
    • 5.2.1F - Processes use memory, a central processing unit (CPU), and input and output.