Skip to content

Variables and Constants

jfraboni edited this page Dec 27, 2014 · 1 revision

Syntax

/*
 * declare a variable called "name" and 
 * assign to it the String value of "John"
 */ 
var name = "John";

/*
 * or within one statement, declare multiple variables
 */ 
var
    nameFirst = "Jack",
    nameLast = "Jones"
    ;

/*
 * declare a constant, the value of which cannot be changed
 */
const BIRTH_PLACE = "Timbuktu";

Table of Contents

Code and Quiz

Code a little

Take the quiz

What Are These Variable and Constant Things Anyway

Variables and constants represent the basic building blocks of applications - they are all the things we create and keep in memory, short term or long term, so we can use them in our application.

When the JavaScript interpreter executes or runs a program, we can ask it at runtime to store a value by a name we provide, and by this, we can look up this value by its name to use at a later time.

Technically speaking, variables and constants are names or identifiers or aliases to locations in memory where we've stored values.

Variables are so called because we can change the values to which they point. By contrast, the value of a constant can never change once assigned.

The Keywords var and const

We create variables and constants using the var or const keyword, followed by the name, or alias we want to use to reference the variable or constant, and optionally we can also initialize the variable or constant to a value:

var nameFirst = "John";
console.log(nameFirst); // prints the String value, "John"

We don't have to initialize a variable to a value, we could merely declare the alias, leaving its value undefined:

var nameFirst;
console.log(nameFirst); // prints the value, undefined

undefined is a special value to signify the variable name has been registered (in the above case, nameFirst), but the variable has yet to be assigned a value.

Valid Names for Variables and Constants

From the Mozilla developer docs:

A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase).

Strickly speaking, there can be no spaces between the words in the name of a variable or constant!

By convention, we name variables using camelcase, where there is not spaces between words in the name, and the first letter of the variable name is lowercase, and each subsequent word in the name starts with an uppercase letter:

var thisIsCamelCase = 'camel case';

By convention, we name constants using all UPPERCASE, separating words by _ underscores:

const GAME_OVER = new GameOver();

Declaration verses Initialization

Quite factually, there is a difference between declaring a variable or constant and initializing one. Declaring really just means we're asking the interpreter to register a variable or constant by its name (or, to use other terms, by its identifier or alias):

var myVariable;

Above, we're simply declaring the variable myVariable. After declaration, the interpreter will know about our variable, but the value of the variable at this stage will be undefined:

var myVariable;
console.log(myVariable); // prints undefined

Initializing a variable or constant is done by simply assigning to it a value using the assignment operator, a singular "equals" character, = :

var myVariable = "My Value";
var myConstant = "My Constant";

While in some cases, non-strict mode execution, you could declare a constant without initializing it, in strict mode, you'd trip an error. Given this and the nature of constants, it's best to always initialize constants at declaration time.

You'll come to know patterns where not immediately initializing a variable may provide more clarity. For example, you might see this pattern before entering a loop wherein you'll assign a value to variable to work with its API inside the loop. Each iteration of the loop will reassign the value of that variable to the next element in the list on which you're looping:

var person;
for (var i = 0; i < people.length; i++) {
    person = people[i];
    // do a lot of stuff with the current person in the people Array //
}

Variables verses Constants

Contextually, you will come to understand when to use either a variable or constant. For example, while a person's birth date is constant, their age is not:

const BIRTH_DATE = new Date(1987, 03, 07);
var age = 27;

You might, for example, want to use constants to list immutable objects, that is, things that will never change, like the states in your application:

const GAME_OVER = 0;
const GAME_LOBBY = 1;
const GAME_PLAY = 2;

Variables

Image I ask you, “Could you please hold this money in your pocket?”, and then I gave you some amount of money, which you place in your pocket. In this example, “money” is the name of the variable, and the “amount of money” is the value of that variable. Again, they are called variables because the value they point to can change, or vary - for example, if your pocket has a hole in it, the amount of money may not stay the same for very long.

var money = 10.00;
money -= 1.00;
console.log(money); // prints 9

When we create variables, we use the var keyword to denote we are creating a variable, and often we assign a value to it at declaration, but not always, we may also declare the variable but not initialize it with any value, which means the identifier is created, but has no value, that is, it is undefined:

var money;
console.log(money); // prints undefined

As best practice, it is often better to initialize variables at declaration, if you can. Consider this example:

var total = 0;
for (index in shoppingCart) {
    total += shoppingCart[index].total;
}
console.log(total); // prints the total value of all items in the shoppingCart, and if none, prints 0

By initializing total to 0, if there's no items in the shoppingCart, the value of total will default to zero, and therefore be immediately usable without having to check if it's defined. Use best practices where you can!

Constants

When we create constants, we use the keyword const and assign a value to it immediately:

const BIRTH_PLACE = "Timbuktu";
console.log(BIRTH_PLACE); // prints Timbuktu

In the Node REPL, after initializing the constant birthPlace, if you tried to change the value, nothing would happen because once set, the value of a constant cannot change:

const BIRTH_PLACE = "Timbuktu";
console.log(BIRTH_PLACE); // prints Timbuktu

BIRTH_PLACE = "North Bay";
console.log(BIRTH_PLACE); // prints Timbuktu

Constants are forever, while in scope!

let

Beginning with JavaScript 1.7, the let keyword allows us to declare a block scope local variable, optionally initializing it to a value. Used inside a block, let limits the variable's scope to that block. See more on using the let here...

###Any Type of Value

Variables and constants can alias any type value, or any type of data - the possible datatypes in JavaScript are:

And while we're at it, variables and constants can also alias these types:

Variables and constants can also point to custom objects that you create!

The Emptiness of Null, the Huh? of Undefined, and the Nagn-ahh of NaN

There's few special types you should be aware of that exist to signify non-existence:

Null

null signifies the value nothing. Often, there's a need to check if a value exists, and for this we compare a variable to null, as in:

if (user !== null) {
  // we know the user exists, so let's do something with the user //
}

Once a variable has a value, that is, is initialized, we can nullify or decommission the variable by assigning it to null. We may want to do this in an application at the point that our variable should no longer be usable:

function logout(user) {
    facebook.logout(user, function(response) {
        if (response.status === 'success') {
            user = null;
        } else {
            console.log('Trouble in paradise!  We were unable to logout for user with id %s', user.id);
        }
    }); 
}

Above in this hypothetical example, we nullify the user Object upon successfully logging out of Facebook.

Undefined

undefined occurs when a name (the id or alias) for a variable or constant was created, but the variable or constant was not initialized to any value.

var name;
console.log(name); // prints undefined

NaN

And also, we have NaN, which stands for not a number. Some static or strongly typed languages will initialize numeric types that have not been given a value to NaN. In JavaScript, the use of NaN is pretty rare, but the value will be returned by Math functions that fail:

console.log((Math.sqrt(-1))) // prints NaN

The Dynamic Nature of JavaScript

Finally, note that JavaScript is a dynamic language. This means you can do some pretty flexible things at run time, like assign a String to a variable that was already initialized to a Number. The dynamic nature of the language means you have to pay attention a little bit more too, because in not not being statically typed, JavaScript is lacking compile-time assurance of type safety preventing type conversion errors:

"...static typing means that programs are checked before being executed, and a program might be rejected before it starts. Dynamic typing means that the types of values are checked during execution, and a poorly typed operation might cause the program to halt or otherwise signal an error at run time. A primary reason for static typing is to rule out programs that might have such "dynamic type errors". - Norman Ramsey

What this means is that we can, for example, assign a the value variable to be a String and later assign to the same variable a value of a different type, like a Boolean, and the program will not crash:

var something = "It's a String";
console.log(something); // prints "It's a String"

something = true;
console.log(something); // prints true

This means, of course, that you must know what you're assigning to your variables such that you don't experience unexpected results. Be vigilant!

© 2014-2015 Operation Spark