Fall 2024 - P4
Big Idea 3 | .1 | .2 | .3 | .4 | .5 | .6 | .7 | .8 | .10 |
Lesson 3.1.3 JavaScript Variables
Variable Naming
In JavaScript, variable names are also case sensitive, meaning that capitalization is important when referring to previously saved variables.
CamelCase
Capitalize every word after the first in the variable name. Variable names must start with a letter. This is standard for variables in JavaScript.
%%html
<script>
playerOne = "Kushi"
</script>
Variables can be used to reference previoiusly stored information, such as user-inputted data or data based on a user’s OS or location.
%%html
<script>
// If you were coding Snake and wanted to change the food the snake was eating and the background color of the game,
// you could do so by setting those values as a variable rather than a single stagnant value
// set a default
let selectedFood = "🍓";
let selectedColor = "PaleGoldenRod";
// Draw the food. Pay attention to selectedFood
let activeDot = function(x, y, isFood = false){
if (isFood) {
const foodSize = BLOCK;
const foodX = x * BLOCK;
const foodY = y * BLOCK;
ctx.font = `${foodSize}px sans-serif`;
ctx.fillText(selectedFood, foodX, foodY + foodSize);
}}
//[...]
// Paint the canvas. Pay attention to selectedColor
ctx.beginPath();
//background color
ctx.fillStyle = selectedColor
//[...]
// Use previous variables to change the food and background color.
// Dont worry about the other code (for loop, iteration, if/elseif statements), just look at the use of variables
if (food_setting[i].id === "strawberry") {
selectedFood = "🍓";
selectedColor = "PaleGoldenRod";
} else if (food_setting[i].id === "croissant") {
selectedFood = "🥐";
selectedColor = "Plum";
} else if (food_setting[i].id === "cheese") {
selectedFood = "🧀";
selectedColor = "Orchid";
} else if (food_setting[i].id === "burrito") {
selectedFood = "🌯";
selectedColor = "PaleTurquoise";
} else if (food_setting[i].id === "soup") {
selectedFood = "🥫";
selectedColor = "LightSlateGrey";
}
</script>
Declaration
Variables in JS can be declared in 4 different ways:
- automatically
var
let
const
ALWAYS declare your variables before using them to optimize your code and prevent errors. If you were reading a book and came across an unfamiliar word, you would want to find its definition before that page and not after. Computers are the same way and prefer to find your variables before needing to call them.
IMPORTANT NOTE
Printing variables is different in JS than in Python. Python can print statements using print(variable_name)
, but JS is different, especially for those using KASM on Chromebooks.
Print statements in JS using console.log(variableName)
. HOWEVER, these printed statements will NOT show up in VSCode. You will have to go to your Console to view these printed statements.
Access the console by going to any web page (preferrably a page that you have code on) and doing right-click > inspect OR using Ctrl+Shift+I
or Command+Option+I
on Mac and then clicking on Console at the top.
If this doesn’t work or the inspect box is grayed out, then you might be logged into your school account, which blocks inspect. Switch accounts to leave your school account and try it again. IF YOU ARE ON A CHROMEBOOK, YOU WILL NEED TO LOG INTO YOUR COMPUTER AS GUEST TO BYPASS THIS BLOCK.
Automatically
Automatically declaring a variable is the easiest way to do so; simply name and then define a variable
%%html
<script>
studentName = "Maryam";
studentAge = 17;
studentBlonde = false;
console.log(studentName, ",", studentAge, ",", studentBlonde)
numberOne = 12;
numberTwo = 26;
numberThree = numberOne + numberTwo;
console.log()
console.log(numberOne)
console.log(numberTwo)
console.log()
console.log(numberThree)
console.log(numberOne + numberTwo) //see 3.1.4 for more on addition and concatenation in JS
</script>
Var
Var
is a depreceated, or no longer/rarely used, way to declare variables. Var will put a variable at the top-most, or global, scope and will overwrite other variables above it. Avoid using var when possible.
If you use var
outside a function in the general “body” of your code, it can be used anywhere within your code. If you use var
within a function, it can be used freely within that function.
%%html
<script>
var studentName
var favoriteColor = "blue";
var favoriteNumber = 25;
var isAlive = true;
console.log(favoriteColor)
console.log(favoriteNumber)
console.log(isAlive)
function exampleFunction() {
var flowerName = "peony";
var petalNumber = 300;
console.log(studentName, "'s favorite flower is", flowerName, ", which has", petalNumber, "petals.");
console.log(studentName, "'s favorite color is", favoriteColor, "and also likes the number", favoriteNumber);
console.log(studentName, "is alive, because when I return the variable isAlive, I get the result", isAlive);
}
exampleFunction();
// note the function syntax.
// start with function, then write the functionName() with parenthesis and a curly bracket after.
</script>
Let
Let
is used when a variable could possibly change. It’s the preferred way to declare variables in JS.
Let is block-scoped, meaning it can only be used within the block it is defined in (curly brackets {}
, square brackets []
, etc)
%%html
<script>
let fingers = 10;
if (fingers == 10) {
let reliefStatement = "Thank God!"
console.log(reliefStatement)
}
</script>
If we try it again…
%%html
<script>
let fingers = 10;
if (fingers == 10) {
let reliefStatement = "Thank God!"
console.log(reliefStatement)
}
// Lets try printing this variable outside of the block
console.log(reliefStatement)
// Notice how it only worked the first time.
</script>
Let can be updated but not redeclared.
%%html
<script>
// this works
let fooBar = 21;
fooBar = 27
// this does not
let bazQux = "Me";
let bazQux = "You";
</script>
Side note: Names like “foo”, “bar”, “baz,” and “qux” are placeholder names often used in tutorials. Full list here
Const
Const
is short for constant and is used when a variable doesn’t or shouldn’t change. This is also acceptable to use in JS. Const is also a block-scope variable.
Const cannot be updated or redeclared, so make sure to pick unique variable names when using this prefix. This does not apply when const is used as a way to declare an object (explained in 3.1.4), as you can update properties of an object after the fact.
%%html
<script>
// these variables will never change
const windowHeight = 580;
const greetingText = "Hey there, stranger!";
// object example
const strawberryProperties = {
berryColor: "red", // seperate variables within an object using commas
hasSeeds: true,
berryCount: 20,
}
// update your object
strawberryProperties.berryCount = 40;
</script>
Here’s a bad example:
%%html
<script>
const strawberryProperties = {
berryColor: "red",
hasSeeds: true,
berryCount: 20,
}
// you cannot do this
strawberryProperties = {
hasStem: true,
statement: "Mmm, yummy!"
}
</script>
Popcorn Hack:
Update an object declared using const correctly
Hack #1
- Define variables automatically using let and const.
- Write console.log() statements and demonstrate knowledge of accessing the console correctly
- Short function that correctly calls each variable and string them together to make a sentence.
- Make sure to follow camelCase
- Create code cells to declare, or define, your variables and variable types
- Use comments to explain your code
- Use console.log statements to view the values of your variables