Variables
Just like in previous lessons. I have convinced you that you already understand the concept of variables. This case is no different. Think of the words we use. What are they? They are basically variables because they store data and the data they store is what they represent. Phone is a variable that represents a specific series of devices. So much so that in the current day phone has other variables in it like camera, calculator, web browser, general purpose computer and so on. The words we use are not the thing. The thing is the thing. The words just represent the thing which makes it a variable. We can use variables in more advanced ways when you get past the basic concept. Like putting a function into a variable.
We can put functions into variables
const $variable_function = function() {
'This console log is coming from a function that is stored in a variable!';
};
console.log($variable_function);
We can put html elements into variables
const $some_element = document.querySelector('.flex div:nth-child(2)');
The flexbox above's middle box's border is being controlled by a variable that contains the div and a class that was added to it using js which we have used in the CSS which has the property border and value 1px solid red. (see main.js Line:25 and style.css line:162).
const $flex_child = document.querySelector('.flex div:nth-child(2)');
$flex_child.classList.add('change-flex-child');
We can put the value of some thing like an input into a variable
const $variable_text = document.getElementById('variable-text');
$variable_text.addEventListener('change', (e)=> {
let $variable_text_value = $variable_text.value;
console.log(`The text you put is: ${$variable_text_value}`);
document.querySelector('.variable-text-value-box').innerText = `The text you put is: ${$variable_text_value}`;
});
Load the JS after the DOM
There are various ways you can tell the JS to load AFTER the DOM loads. Here are a few
DOMContentLoaded
Below we say:
document.addEventListener(DOMContentLoaded, (e)=> {
console.log('The site is fully loaded');
// All of your JS code now goes in here
});
Use defer in the script tag
<script defer src="/scripts/main.js" >
Defer makes sure the script tag is postponed until after the document is loaded
Just put the script tag at the bottom of the document
Put the <script> tag at the end of the document, right before the closing /body tag. Because the html is rendered character by character, line by line. If you load the script last it will load last.
Template Literals & Expressions vs Concatenation
A better way of passing variables through a string
Concatenation🥈
Before if you wanted to use a variable in a string you had to concatenate it using + to add the variable to the string
'This is the string within the single quotes' + var_name + 'This is another string'
Template Literals🥇🏆
Now we can just use backticks `` write the string within the backticks and pass a variable in using ${}
`This is a string within the backticks ${var_name} ← is a variable. Everything can go in here! Much easier ya?`
Loops
Loops will loop through some code until or depending if some condition is met.
There are 6 types of loops, all execute depending on certain conditions that happen at different times.
for | When the number of iterations is known |
while | When looping should continue until a condition is false |
do...while | When the loop must execute at least once, then continue based on a condition |
for...in | Looping over object properties |
for...of | Looping over iterable values (arrays, strings, sets, etc.) |
.forEach() | Iterating over an array with a callback function |
for Loop (Standard Counting Loop)
Used when you know how many times the loop should run.
for (let $number = 0; $number < 10; $number++){
console.log($number);
};
while Loop (Condition-Based Loop)
Used when looping should continue until a condition becomes false
let x = 10;
let y = 1;
while (y <= x) { // While y is less than or equal to x...
y++; // Add 1 to y
console.log(`x is equal to ${x} - y is equal to ${y}`);
};
do...while Loop (Runs at Least Once)
Used when at least one execution is required before checking the condition
let beers = 0;
do {
console.log(`${beers} Beers Dranken successfully! 😵💫`);
beers++;
} while (beers <= 10);
This button is from the practical example
for...in Loop (Object Property Loop)
Used for looping over object properties (not recommended for arrays)
const person = {
Name: 'Maximus',
Job: Professor,
City: 'Toronto'
};
for (let key in person){
console.log(key, person[key]);
};
for...of Loop (Iterates Over Values)
Used for looping over iterable values like arrays, strings, sets, or maps
const playingCards = [10, 20, 30];
for (let num of playingCards) {
console.log(num); // 10, 20, 30
};
.forEach() (Array Method for Iteration)
Used for looping through arrays with a callback function
const numbers = [10, 20, 30];
numbers.forEach(num => console.log(num)); // 10, 20, 30
Math
For Quick Maths
In part 1 of the JS cheat sheet, we purposefully avoided math. This time around we will dive into the basics.
Basic Math Stuff
To do basic math you can do it with or without variables and use the operands:
+ Plus
- Minus
* times
/ Divide
** Exponentiation
++ increment up
-- Increment down
Output to console some math with no variables
console.log(20 + 33);
Using variables
const a = 5;
const b = 10;
console.log(a + b);
The Math object
The Math object can be used to run different maths. There are many of these.
Math.E | // returns Euler's number |
Math.PI | // returns PI |
Math.SQRT2 | // returns the square root of 2 |
Math.SQRT1_2 | // returns the square root of 1/2 |
Math.LN2 | // returns the natural logarithm of 2 |
Math.LN10 | // returns the natural logarithm of 10 |
Math.LOG2E | // returns base 2 logarithm of E |
Math.LOG10E | // returns base 10 logarithm of E |
// You can return them on their own or put them into a variable
let c = Math.PI;
console.log(`The number PI is: ${c}`);
// Math Methods. You can use them to perform various math tasks.
// Math.round() Round to the nearest whole number
console.log('Math.round():' + Math.round(2.2));
// Math.ceil() Round up
console.log('Math.ceil(): ' + Math.ceil(2.2));
// Math.floor() Round down
console.log('Math floor: ' + Math.floor(20.4));
// Math.pow() Power of
console.log('To the power of ' + Math.pow(2, 5));
// Math.sqrt() Square Root
console.log('The square root ' + Math.sqrt(50));
// Math.abs() Return an absolute number (prevent negative numbers)
console.log('Absolute Number ' + Math.abs(-200));
Data Types
All of the data we work with has a type
In JS this is not as in your face as other languages. But it is still good to be aware of them.
Nesting Functions
You can put functions within functions
function outer() {
outputBoxOuter.innerText = 'This is the Outer function!';
function inner() {
outputBoxInner.innerText = 'This is the Inner function!';
};
inner();
};
outer();
Logical Operators
Logical Operators are used to check multiple conditions.
It is no different then when you say something like "if it is sunny AND warm out, we will go to the beach ☺️
You are used to checking single conditions:
myValOutPutBox = document.getElementById('myValOutputBox');
let myVal = 1;
let myVal2 = 5;
let myValSum = myVal + myVal2;
if(myValSum <= 10) {
myValOutPutBox.innerText = `The sum of myVal and myVal2 is ${myValSum} which is less then 10 `;
}
else
{
myValOutPutBox.innerText = `The sum of myVal and myVal2 is ${myValSum} which is more then 10 `;
}
We can ramp this up by using logical operators
Beach Time App using NOT - !
Beach Time App will tell the user if the weather is good for the beach or not by comparing what kind of day it is out.
const weatherText = document.getElementById('weatherOutput');
const sunnyDay = 'sunny';
const foggyDay = 'foggy';
const rainyDay = 'rain';
const cloudyDay = 'cloudy';
let todaysDay;
todaysDay = sunnyDay;
// compare the day and if it is NOT a sunny day... Tell the user NOT to go to the beach.
// Note that the below could also be:
// if (todaysDay == foggyDay || rainyDay || cloudyDay) {}
if (todaysDay !== sunnyDay) {
weatherText.innerText = `Today's weather is NOT good for the beach! 🚫😑`;
}
else{
weatherText.innerText = `Time for the beach! ☀️ it is a ${todaysDay} day out! 😊`;
};
Output of the weather app ⤵️
Lucky Number Check Using OR ||
Below we will: create 2 lucky numbers in variables and then put the user's lucky number in a variable as well.
After that we will say: if the users lucky number is exactly like either of the lucky numbers, using the OR operator, print out the innerText telling the user that they have a correct number, else we will tell the user they did not get any of the right numbers
const randoNumberOutputBox = document.getElementById('randoNumberOutput');
let luckyNumber1 = 5;
let luckyNumber2 = 23;
let userLuckyNumber = 23;
if (userLuckyNumber === luckyNumber1 || userLuckyNumber === luckyNumber2) {
randoNumberOutputBox.innerText = `Today is your lucky day, your lucky number is one of the numbers!`;
}
else
{
randoNumberOutputBox.innerText = `Your number is not correct. Better luck next time!`;
};
Output for the lucky number checker ⤵️
Number checking using AND &&
let uNumber1 = 23;
let uNumber2 = 34;
let someLuckyNumber1 = 23;
let someLuckyNumber2 = 34;
if (uNumber1 == someLuckyNumber1 && uNumber2 == someLuckyNumber2) {
console.log(`Your numbers are right!`);
}
else
{
console.log('You Lose!');
};
Storage
Local Storage
localStorage will persist until the user manually clears it out. So even if the tab is closed it will persist when the user comes back to the site.
Basic Syntax
localStorage.setItem('key', 'string');
localStorage.removeItem('key');
localStorage.getItem('key');
Enter Your Name:
It will persist even if you close the tab ⤵️
Session Storage
Session storage will not persist after the tab is closed but will persist if the page is refreshed.
Basic Syntax
sessionStorage.setItem('key', 'string');
sessionStorage.removeItem('key');
sessionStorage.getItem('key');
Enter Some Text:
It will persist if the page is refreshed ⤵️
Cookies
Cookies store data on the users computer in a text file.
Basic syntax
document.cookie = 'Some data'
Make a cookie (only works online or on live server)
In the web inspector, see the cookie in: Application > Cookies > file://
Feature | localStorage |
sessionStorage |
cookies |
---|---|---|---|
Data Storage Duration | Until manually cleared | Until the session ends (browser/tab is closed) | Can have an expiration date or last until the session ends |
Data Storage Limit | ~5MB per domain | ~5MB per domain | ~4KB per cookie |
Scope | Accessible from all tabs and windows under the same origin | Only accessible in the same tab | Accessible across browser requests and sent to the server |
Access Type | JavaScript (client-side only) | JavaScript (client-side only) | Sent with every HTTP request (client-server) |
Persistence After Browser Restart? | ✅ Yes | ❌ No | ✅ If expiry is set, otherwise no |
Security Concerns | Less secure (can be accessed via JavaScript) | Less secure (can be accessed via JavaScript) | Can be stolen via XSS, sent with every request, increasing risk |
Use Cases | Storing user preferences, themes, or saved drafts | Temporary data like form inputs or multi-step form progress | Storing authentication tokens, user sessions, tracking info |
Use localStorage for long-term storage of user settings or data that persists across visits.
Use sessionStorage for temporary data that should disappear when the user leaves the page.
Use cookies when data needs to be sent to the server (e.g., authentication tokens).