Codenplay

Variables

Summary

Definition

Variables are just labeled pieces of data (for example numbers or strings). Variables can be changed during the program execution.

Variable declaration

To declare a new variable we use special word var

var x;
var home;

Assigning a value

To assign a value to a variable we could use a special instruction =

x = 12;
// or
x = 'Hello';
// or
x = 3 + 3;

Usage

To use variables in the code we just write their name

var x = 3;
move(x);
// or
move(x + 12);

Variables is a very important programming concept. It is a base of short memory in the program.

Motivation

We often want to pass and store data during the program execution — for example, if we have a program that adds 2 numbers, received from the user, and prints the result to the screen. We need to store these numbers somewhere in the program. Variables can help us to do this.

Variables

Variables are just labeled pieces of data (for example numbers or strings). Variables can be changed during the program execution. We can imagine that variables are boxes with different names and some content inside. Each box has a different and unique name.

What can be stored

Variables can store numbers and strings (actually, a lot of other stuff, but let’s skip it to avoid information overload).

Variable declaration

As you remember, a program consists of instructions, expressions, and declarations. Let’s see an example of declaration. A variable declaration is just like the creation of a new box with the name we want.

To declare a variable in javascript you could use the special word var

var x;
var home;

Please note that when we declare a variable we just create a new labeled box, but we don’t put anything there, so the box (or the variable) remains empty.

Assigning a value

An empty box (or variable) is not very useful, so let’s learn how to put something inside it. To assign a value to a variable (or to put something inside a box) we could use a special instruction =

x = 12;
// or
x = 'Hello';
// or
x = 3 + 3;

If we try to assign a value to a variable that does not exist, the program will show an error.

Value update

Each box has enough space for only one number (or string). So if we assign a new value to some non-empty variable, its old value just disappears (i.e. before we put something in a box we should get everything out of it).

Usage

We can connect a variable declaration with a variable assignation

var x = 3;
var x = 3 + 5;

In this way we can keep program code shorter and more readable.

To use variables in the code we just write their name

var x = 3;
move(x);
// or
move(x + 12);