JS Variables Lesson
This lesson explains how to use JavaScript variables.
- TINKERERS
Presented by the
TINKERERS
Variables Lesson Intro
In this lesson, you will be learn the basics of variables. This includes what they are, how to use them in Javascript, and where they can be applied. Let’s dive in!
What a Variable Even Is
- A variable is a container that can store information
- Analogy: Cardboard box where you can put notes or whatever you want in
%%html
<style>
button {
margin: 0.5rem;
padding: 0.7rem 1.2rem;
font-size: 1rem;
border: none;
border-radius: 8px;
background-color: #2563eb;
color: white;
cursor: pointer;
transition: background 0.2s;
}
button:hover {
background-color: #1e40af;
}
#output {
margin-top: 2rem;
font-size: 1.2rem;
padding: 1rem;
border: 2px solid #ddd;
border-radius: 10px;
width: 300px;
}
</style>
<h1>JavaScript Variable Demo!!</h1>
<p>Click the buttons to see how a variable changes.</p>
<button onclick="declareVariable()">Declare Variable</button>
<button onclick="updateVariable()">Update Variable</button>
<button onclick="showVariable()">Show Variable</button>
<button onclick="resetVariable()">Reset</button>
<div id="output">Variable not declared yet.</div>
<script>
let score;
function declareVariable() {
score = 0; // initialize it
document.getElementById("output").textContent =
"Variable declared! score = " + score;
}
function updateVariable() {
if (typeof score === "undefined") {
document.getElementById("output").textContent =
"Declare the variable first!";
return;
}
score += 10;
document.getElementById("output").textContent =
"Variable updated! score = " + score;
}
// Show the variable
function showVariable() {
if (typeof score === "undefined") {
document.getElementById("output").textContent =
"Variable is undefined (not declared yet).";
} else {
document.getElementById("output").textContent =
"Current score: " + score;
}
}
// Reset everything
function resetVariable() {
score = undefined;
document.getElementById("output").textContent =
"Reset complete. Variable is undefined again.";
}
</script>
JavaScript Variable Demo!!
Click the buttons to see how a variable changes.
How we used variables
In our wordgame from last sprint, we used variables to:
- Store strings that would be typed by a user
- Store the time the user started
- Store the accuracy once it’s calculated
- etc.
Examples of Variables in our Wordgame
Look below for an example of a variable in our wordgame!
const short_strings = ["The quick brown fox jumps over the lazy dog", "Pack my box with five dozen liquor jugs", "How quickly daft jumping zebras vex", "Jinxed wizards pluck ivy from the quilt", "Bright vixens jump dozy fowl quack", "Sphinx of black quartz judge my vow", "Two driven jocks help fax my big quiz", "Five quacking zephyrs jolt my wax bed", "The five boxing wizards jump quickly", "Jackdaws love my big sphinx of quartz", "Quick zephyrs blow vexing daft Jim", "Zany gnomes fix blighted quartz vases", "Bold foxes jump quickly past the lazy hound", "Mix two dozen plums with five ripe figs", "Anish is the GOAT"];
Here’s another example of variables being used at the beginning of Word Game.
const wordCanvas = document.getElementById('wordCanvas');
const wordCtx = wordCanvas.getContext('2d');
const optionsButton = document.getElementById('options');
const progressFill = document.querySelector('.progress-fill');
const progressText = document.querySelector('.progress-text');
const wpmEl = document.querySelector('.wpm');
const accEl = document.querySelector('.accuracy');
if (wpmEl) { wpmEl.style.visibility = 'hidden'; wpmEl.textContent = ''; }
if (accEl) { accEl.style.visibility = 'hidden'; accEl.textContent = ''; }
let currentString = "";
let userInput = "";
let startTime = null;
let finished = false;
let mistakes = 0;
let currentPrompt = "";
let caretInterval = null;
General Examples of Variables
Here are some examples of variables:
%%javascript // This line is needed to run JavaScript in a Jupyter notebook cell
var hello = "Hello, I am a string.";
let hi = 0;
const hey = 3.4;
<IPython.core.display.Javascript object>
Now let’s answer the following questions:
- What do the keywords
var
,let
, andconst
do?- How are they different?
- What are
hi
,hello
, andhey
? - What does the
=
symbol do? - What are the values after the
=
?
Lesson Cont…
Now since we have an initial feel for variables, let’s continue our investigation into the subject.
Variables can be declared by var
, const
, and let
.
IMPORTANT: var
is now deprecated, so it is best practice to not use it. It’s the old way of defining variables, so avoid using this one.
const
REQUIRES a var to never change later. We use let
if we want to change the var later.
Defining variables
To define variables, use var
, const
, or let
as your keyword, followed by the name of your variable, an equal sign, the value assigned to the variable (optional), and a semicolon. You should try to make your variables descriptive but not too long.
Here is a common naming convention for JavaScript variables:
- All lowercase if variable is just one word
- camelCase is variable is 2+ words
Examples
// Defines a variable named score with value 20.
let score = 20;
// Here, a variable has been defined but its value is undefined.
let age;
/*
When we change the value of a variable after defining it with let/const/var,
you DON'T need to redefine it again - i.e. you don't need to use let, const
or var again.
*/
age = 67;
// What does myvar refer to? What does it represent?
// You should avoid vague names like below.
// Variables should be concise and descriptive.
const myvar = 3;
// This will raise an error, as constants are... well... constant
// myvar = 20;
// You should also avoid variable names that are ridiculously long.
// (this is exaggerated but please don't do this lol)
let accumulatedScorePointsVariableUsedForDeterminingFinalOutcome = 20;
In Our Wordgame…
In our wordgame, we used const
to define the lists of possible strings since we aren’t going to change the list of strings that the user might have to type. We also properly named our variable, and used an equal sign to declare the var to it’s specified value.
Equal Sign
Did you try removing the equal sign?
Removal of the equal sign would have caused an error. the =
symbol is what TELLS javascript that a variable is being declared and initialized. The let
and const
keywords are there to say what type of variable we are using.
Popcorn Hack 2
It’s time for a 2nd poporn hack!
A brief note on Data Types
As you may have noticesd, there are a lot of different kinds of values we can store. These are called data types.
Going very in-detail on data types is outside the scope of this lesson, but here’s a brief overview with examples from Word Game.
- Number
- Some other programming languages have integers and floats.
- JavaScript has just one data type called
Number
. - In word game, the variable
mistakes
contained a number.
- String
- A “string” of text surrounded by quotes.
- In word game, this code
let currentString = "";
gives currentString the value of an empty string. - Warning: “16” and 16 are DIFFERENT because one is a Number and one is a String.
- Booleans
- True/False values
- In the
finishGame()
function in Word Game:finished = true;
- Note that we didn’t need to use
let
, as we had already done that
- Note that we didn’t need to use
- Null
- To represent an intentionally empty value.
- Word Game example:
startTime = null;
just tells the computer that startTime has a empty value. - This is different from
undefined
, which is set by JavaScript- For example, when you define a variable like
let x;
, x will be undefined until given a value
- For example, when you define a variable like
- And others! (Object, BigInt, Symbol, Date, etc.)
Ending notes
Nice! You’ve learned about variables and used higher-level thinking skills! For our lesson’s end, we will give you this cheat sheet:
In a JS declaration such as this:
%%javascript // This line is needed to run JavaScript in a Jupyter notebook cell
let var_name = "Value";
let
can be replaced withconst
if you aren’t changing the var name later.var_name
can be replaced with any valid variable name (any alphanumeric charecter or the_
, cannot start with a number)=
is necessary for proper declaration"Value"
can be changed to any value that you want to store, whether a string or a number
Ending
That’s it for the lesson! Remember to try the homework as well! It should take ~30min!