Variables & Data

So, you've mastered the Hello World! program and you want to move forward? Excellent. Let's talk about storing and manipulating Data.

A variable holds information, numbers, words: data. It gives the programmer the ability to store, manipulate, retrieve, and output information. Some programming languages are "Typed" languages. They have a specific kind of variable, depending on what you want to do. This is important because different types of variables require different amounts of memory (RAM) in the computer. C++ and Java are strongly (or statically) typed languages. Here are a few variable types, the amount of memory they require, and their limitations:

DATA TYPE

CONTENTS

SIZE (IN BYTES)

RANGE

short int

Whole Numbers

2

-32,768 to 32,767

int

Whole Numbers

4

-2,147,483,648 to 2,147,483,647

unsigned int

Positive Whole Numbers

4

0 to 2,147,483,647

char

Single Character

1

-128 to 127

float

Numbers, including decimal values

4

17×1038 to 1.7×103817\times10^{-38} \text{ to }1.7\times10^{38}

bool (or boolean)

True or False

1

0 to 1

String

Text*

Varies

Char[] array

*Strings are not a primitive data type, they are an array of chars or a special type called an object. More on data types: C++: https://www.geeksforgeeks.org/c-data-types/ Java: https://www.geeksforgeeks.org/data-types-in-java/ Javascript: https://www.geeksforgeeks.org/variables-datatypes-javascript/

When creating a variable in strongly typed languages, the programmer needs to know exactly what the variable will be holding. The micro-management of memory and data types is what makes C++ such a strong language for things like video games.

Javascript is not a strongly typed language. Neither is Python, Ruby, Perl, or Lua. They are what we call dynamically typed. They can transition between variable types and do not require the programmer to declare what type of variable is required. The interpreter will even convert a character to a number and back again, as needed.

Javascript uses a keyword to create (declare) a variable. There are three different keywords, each with a special meaning:

// can hold all sorts of data and is globally scoped (more on scope later)
var myVariable;

// can hold all sorts of data and is locally or block scoped
let myOtherVariable;

// can hold all sorts of data but that data cannot change (or shouldn't, at least)
const myConstant;

For this course, it would be best if we use let as often as possible.

I don't expect everyone to read it, but here is a great chapter on variables in JS.

The "const" declaration in JS does not necessarily mean the variable cannot change. This is a strange property of Javascript and is above the scope of this course. If you'd like to learn more, you can search "javascript immutable const".

Last updated