What is a variable?
A variable is simply a place to store something. In fact, you can think of a variable like a cupboard. First, we need to create the cupboard to store stuff in. Next, we’ll want to put something in the cupboard. Then later, we’ll want to retrieve the item and use it. We might also want to replace the item with another item.
Time to see it in use! Let’s say we wanted to alert the number
25. Normally, we’d do it like so:
But what about doing this using a variable? Here’s how:
var x = 25; alert(x);
Let’s take a look at what’s going on here- first of all, we’re creating (aka declaring) our variable called
x by saying
var x. On this same line, we’re also giving the variable an initial value to store by saying
Now, when we run this code it will alert
25! This is because
x is now just a placeholder for the number 25. It is just like if you were editing a document and wanted to replace all instances of the word “banana” - in this case, the browser goes through our code and replaces all instances of the variable
PS: Follow along! Create a new file called
index.htmland add the following code:
But why does any of this matter? Well, the true power of variables is the fact that you can change them. For example:
var x = 25; x = 85; alert(x);
As you can see, setting a variable that had already been declared is as simple as saying
x = 85. You don’t need the
var bit, as it’s already declared.
Now, we can alert
85 without even changing the line where it says
Types of variables
A string is another way of saying some text. We have to surround it in quotes because otherwise it would be considered a variable. Here is an example:
var x = "I am a string!";
It doesn’t matter if you have single or double quotes:
var x = 'I am a string!';
Obviously, we can also set a variable to a number - like we did before! It can be a whole number:
var x = 16;
Or a decimal:
var x = 3.14;
Booleans are simply
var x = true; var y = false;
This may sound very simple, but they can come in handy when using
if statements - which let you execute bits of your code based on whether statements equal
Yay! You now know all about variables! Let’s go through what we’ve learned today.
First of all, we learned how to declare, set and change variables:
var x = 12; /* Declared and set a variable */ x = "Helloooo!"; /* Change a variable (you can change it to a different type) */
We also learned about some of the basic types of data:
I’m honored to be part of your coding journey, and I hope you found this useful! If so, why don’t you join the newsletter and receive more articles like this in your inbox? Plus, I’ll love you in return <3
Also, if you are really nice and have $4 to spare, I’d really appreciate it if you buy me a coffee ☕. Thanks!
false values. See you then!