Last time we looked at the various types of data we can store and work with in Javascript. This time we’ll look at variables, which allow us to actually store these values.
A variable is a name we give to both a place to put values, and the value that is currently in that place. We can replace the value in that position by assigning to it, or otherwise manipulate the value.
Here is an example of creating a variable in Javascript:
let myvar;
Let is a special word that tells Javascript we’re declaring a new varaible. Originally Javascript used the word ‘var’. While you can still use var today, it has some surprising behavior and isn’t recommended for new code. I mention it only so you aren’t surprised if you come across it.
Any code that comes after the variable declaration can use it. The name of a variable is itself an expression. When Javascript needs to determine the value of a variable expression, it just looks it up.
Here’s an example:
let name;
name = prompt("What is your name?");
alert("Hello there " + name);
This is just like an earlier exercise, but now a little easier to read.
The first line declares a variable called name
. Initially, that box
isn’t holding anything. Then we display a prompt, and store the
input into the name
variable. Finally, we use the name
variable
when producing the message to display to the user.
Note that this code functions the same as our earlier approach:
alert("Hello there " + prompt("What is your name?));
The benefit to the code that uses the variable is that
It is very common to create a variable and assign a value to it immediately. Javascript allows a bit of shorthand, though the two approaches are identical :
let name;
name = "Joe";
// Is the same as:
let name = "Joe";
A quick mention, that line that starts with //
is a comment. Javascript
ignores anything on a line after //
, so you can use this to add
notes or documentation to your code.
Variables can be reassigned as many times as you want.
let account_balance = 0;
// a += 3 is shorthand for a = a + 3;
account_balance += 10;
account_balance -= 5;
account_balance += 3;
You can use almost any name for a variable, except:
Scope refers to where in your code a varaible is visible. The simple rule is that variables can be seen after they are first declared. You can also create more localized variables, that can only be seen in a smaller window. Curly braces create a new scope. Any variables declared inside that inner scope cannot be seen outside it.
let message = "Hello ";
{
// this is a new scope
// we can still see name inside here
// but anything we create here cannot
// be seen outside.
let name = prompt("What is your name?");
// If the user entered a first and last name,
// only keep the first piece before the space.
name = name.split(' ')[0];
message += name;
}
// Here, outside the scope, name is not visible.
// But since message was declared in this outer scope
// message still is.
// This will alert the message including the name.
alert(message);
The example above can give you a little sense of why we might want to create these inner scopes. In this example, we dont need the original full name, so we’re okay just using it to build up message.
There are some later javascript features that create their own scope automatically, so the example above was mostly for demonstration purposes.
There’s one more little quirk with these nested scopes. If you have a variable defined in multiple nested scopes, the name refers to whichever one was defined most recently.
let name = "Joe";
{
// The only 'name' variable
// in scope is the one up above.
console.log("Hi " + name); // displays Hi Joe
// Creates a new variable named 'name' in this inner scope.
// Now later code in this scope that uses name will refer
// to this one.
let name = "Frank";
console.log("Hi " + name); // displays Hi Frank
}
console.log("Hi " + name); // displays Hi Joe
This can be a bit confusing at first, but don’t worry. In practice, this doesn’t come up often, and good naming can prevent this name shadowing. However, it does happen on occasion, and it is good to understand.
That is all there really is to know about variables.
At this point you have the knowledge required to start writing longer programs. You probably want the ability to save your work. With Javascript, you have a few options. You can download and install Nodejs, which lets you build Javascript programs that run outside the program.
If you want to continue working within the browser, like this class, you can save this file. It contains a minimal webpage, and a space for you to write your javascript code. When you open it in a browser, it will run your javascript just as if you had typed it in line-by-line. If you open it in a text editor, like nodepad or perhaps something like Sublime Text, you can edit your code.
What is wrong with this code? (In fact, this shows you how syntax highlighting, where your editor understands your code, can help catch issues)
let 1st_name = "Angela";
What will be the output of the following code?
let balance = 123;
{
console.log('current balance: ' + balance);
let balance = 5;
console.log('new balance: ' + balance);
}
balance += 5;
console.log('final balance: ' + balance);
current balance: 123 new balance: 5 final balance: 128
Next up we’ll look more at functions, and how we can create these reusable pieces of code ourselves.