Spelchan.com Logo

From Scratch Web Games: A Beginners Guide to Game Development using HTML, CSS, and JavaScript

Chapter 4.4: Variables

Why we need a scripting language is because more complicated pages have to track the state of things on the page and be able to alter things when actions, such as the user clicking on a button, changes the state of the page. We call things that have a set of possible values that can change a variable.

A variable is essentially a label that refers to a bit of information, such as a name. While there are different types of variables, JavaScript doesn't care what information the variable contains. With JavaScript, you can change the type of information that a variable contains simply by assigning a different data type to that variable. This is known as dynamic typing. It is also a big source of errors which is why many languages do require that you have specific types of variables for holding specific types of information. The popularity of TypeScript, which is essentially JavaScript with enforced data types, is due to how many problems dynamic typing causes. Later versions of the ECMA-Script specification do support optional types which is a good compromise.

To use a variable, you need to give a name to that variable. The name of a variable can not be the same as one of the commands that JavaScript has, which we call reserved words. The first character of a variable must be a letter, and underscore, or a dollar sign. The rest of the name can consist of letters, numbers, underscores, and dollar signs. Spaces can not be used in the variable name. While there are many Unicode characters that can also be used, it is best not to so we will not go into details.

Another important factor about naming variables is the fact that JavaScript is case sensitive. This means that the language treats the letter ‘a’ different from the letter ‘A’. So you can declare bob, Bob, BOB with each of them holding separate values.

JavaScript was deigned to be a scripting language meant to just write very small programs for handling page contents. The idea of writing a web application in JavaScript was inconceivable at the time it was created so the language was designed for a different purpose. Having global variables for a single simple page is not necessarily a bad thing, even though we consider global variables to be a bad practice. This means that you can create a global variable by simply using a variable name and assigning it a value. Unfortunately, this means that if you mistype a variable name, you will have a hard to find bug in your program.

thisIsAGlobalVariable = 666;
$Another_global_variable = 13;

You will notice that we can assign a value to the variable by using the equals sign followed by a literal value. You will also notice that we end the line with a semi-colon. You should avoid using global variables. There are three ways of declaring variable legitimately: const, var, and let. Let’s take a look at them individually.

The const keyword is a new keyword so older browsers may not support it. Using const will create a variable that can not be reassigned, meaning once declared you can not change the value. If it is referring to an object, such as an array, that object can change so we will consider const to be a valid way of setting up a variable.

const DEGREES_IN_CIRCLE = 360;
DEGREES_IN_CIRCLE = 2 * PI; // invalid, can’t redeclare
DEGREES_IN_CIRCLE = DEGREES_IN_CIRCLE * 2; // invalid, changing value is still redeclaration

The var keyword was original way of defining variable but all variables are placed on the function’s scope. We will be explaining scope when we look at functions later in this chapter.

var oldWay = "var";
var bob = 1;
var Bob = 2; // remember, not the same as bob
var BOB = 3; // remember, not the same as bob or Bob

The let keyword uses the scope of where the variable was defined. Scope refers to where a variable can be used and will be useful once we get into functions and loops so will explain the concept in more detail then. This is the preferred way for defining a variable and should be what you use unless you need to support older browsers that do not support the let keyword.

let bestWay = "let";
let bob = 1;
let Bob = 2; // remember, not the same as bob
let BOB = 3; // remember, not the same as bob or Bob

You set a value to a variable by using the equals sign. In JavaScript the equals sign by itself means assignment and is used for assigning a value or the results of an equation to the variable. Once a variable has been declared, you can change the value that was assigned to it (unless the variable is a const) by simply using the variable name and the assignment operator (=) then providing the new value. Variables can be set to numeric values, String values, and can even be a function or instance of an object. We will discuss these things in further detail in later sections and chapters. Here is a bit of sample code that shows various variables being assigned values.

let x = 11;
x = 7; // x no longer is 11 but is now 7
let text = "Strings need to be enclosed in quotes";
text = "Strings can be replaced with new strings";
let function_variable = function() { /*code here*/ };
text = x; // now text is 7, a number not a string
x = "x is now a String";

As we want to be able to see output, and it won’t be until the end of the chapter until we get to interacting with HTML elements, we will be relying on the console. To get to the console, you need to use the browsers debug menu to show the console. This varies from browser to browser, but generally would be a menu option in the hamburger (3 horizontal bars) menu.

To send messages to the console we use the format:

console.log("Message");
console.log(“x = “ + x); // will display the message and the value of the variable x

This is taking advantage of things that will be covered later, but seeing output is important so don’t worry about why this works, just know that this is how we get output to the console.

While you don’t need to understand the underlying way computers store and represent data, it does make dealing with data easier to understand. Feel free to skip the next section if you are not interested in the topic at the moment.

Chapter contents

Chapter 4 Contents

4.1 Cheat Sheets

A quick summary of the basics of JavaScript.

4.2 History of JavaScript

A brief look at how JavaScript was written in 10 days.

4.3 Comment Controversy

Comments. Why programmers don't write them, and how they should be written

4.4 Variables

Variables are used to store the state of a program.

4.5 (extra) How Computers Represent Data

Bits, Bytes, and data types.

4.6 Math

Math on the computer similar but some symbol differences.

Math functions

Various math operations can be used through the Math class.

4.8 Strings

Strings are what we call blocks of text and are used extensively.

4.9 Calculating true and false

Determining if a conditional expression is true or false

4.10 if (Conditional statements)

Conditional code using the if statement.

4.11 Nested conditions

If statements can contain other if statements, this is called nesting.

4.12 Switch statement

Switch statements are a way of replacing large number of else if statements.

4.13 Functions

Functions let you put common code into a named function that can be called anywhere.

4.14 Looping

Loops allow you to repeat sections of code until conditions are met.

4.15 Nested loops

Just like conditional statements, loops can be nested but this has some special considerations.

4.16 Accessing the Web page

Scripting languages give us the ability to dynamically change the web page.

4.17 Events

Reacting to the user actions is done by handling events.

4.18 Project: Where’s Wendy

Our project for this chapter is a grid search game.

4.19 Project: Where’s Wendy implementation

My solution to the Project.

← previous section
Comment Controversy
next section →
How Computers Represent Data
Table of Contents