Devember - Learning JavaScript

Day 4

Doing if…else statements. The logic is simple but getting used to the syntax of the code is the tricky bit.

let sale = true;
sale = false;
if(sale) {
console.log(‘Time to buy!’);
} else {
console.log(“Time to wait for a sale.”);

Looking at comparison operators now. I don’t like === and !==. I would prefer just == and !=. Why is it like this?

//Should I eat?
let hungerLevel = 7;
if (hungerLevel > 7){
console.log(“Time to eat!”);
} else {
console.log(“I can eat later!”);

Next onto logical operators, this reminds me of when I studied electronics in school; looking at logic gates.

//Should I sleep?
let mood = ‘sleepy’;
let tirednessLevel = 6;
if (mood === “sleepy” && tirednessLevel > 8){
console.log(“time to sleep”);
} else {
console.log(“not bed time yet”);

Truthy and falsy; funny words! Doing short-circuit evaluations and it’s hurting my head a little trying to translate the long way of doing it into the short way:

let tool = ‘marker’;

let writingUtensil = tool || “pen”;

console.log(The ${writingUtensil} is mightier than the sword.);

I am starting to get it, I think the course just does a poor job of explaining what’s going on.

I like the look of ternary operators; anything to squeeze typing down to a minimum and keep things looking clean!

let isLocked = false;
isLocked ? console.log(‘You will need a key to open the door.’) : console.log(‘You will not need a key to open the door.’);

let isCorrect = true;
isCorrect ? console.log(‘Correct!’) : console.log(‘Incorrect!’);

let favoritePhrase = ‘Love That!’;
favoritePhrase === ‘Love That!’ ? console.log(‘I love that!’) : console.log(“I don’t love that!”);

Next, else if statements, for more complex conditionals.

let season = “summer”;

if (season === “spring”) {
console.log(“It’s spring! The trees are budding!”);
} else if(season === “winter”) {
console.log(“It’s winter! Everything is covered in snow.”);
} else if(season === “fall”) {
console.log(“It’s fall! Leaves are falling!”);
} else if(season === “summer”) {
console.log(“It’s sunny and warm because it’s summer!”);
} else {
console.log(“Invalid season.”);

Finally I end today’s session on Switch statements.

let athleteFinalPosition = ‘first place’;

switch (athleteFinalPosition) {
case “first place”:
console.log(“You get the gold medal!”)
case “second place”:
console.log(“You get the silver medal!”)
case “third place”:
console.log(“You get the bronze medal!”)
console.log(“No medal awarded.”)

I found today quite tough compared to the previous three. I’m not feeling so confident I can remember everything as I have done thus far.

Me again… I did a quick search. == means is basically equal to, and === means is totally exactly equal to.
Javascript is weakly typed, meaning you put numbers, strings and true/false values into vars and compare them all, and javascript isn’t angry about it. If two vars contain a word and a number and you compare/work with both, it will work with it. Similar to boolean values, a 0 and a 1 are commonly how a false and true value are stored respectively. Sometimes a -1 is used to store a false value.
So, if you try and console.log(1 == true), you should get a true since they sort of mean the same thing. However if you do a console.log( 1 === true), you should get a false, because they are not exactly the same thing.
I guess it is a best practice thing, like above. Most of the time it wont cause issues, until it does.

Good work so far!

1 Like

So is == is the same as truthy? Would that make != falsey?

there’s also the shorthand if/else.

const result = expression ? if-true-condition : else-condition

That’s what I used with the locked door, correct answer and favorite phrase code. I really like concise code.

Some argue against it because it is less explicit with what it’s doing. So for small things I would say its fine but once you really throw some big logic in there I’d recommend to stick with the traditional If/else.

I don’t understand what the problem with it is. Just readability?

I had never heard of truthy or falsy… Javascript developers are a special bunch :slight_smile:

Not exactly the same thing. Truthy just means things that are the same as a boolean value of true. Pretty much any non zero variable you can compare.
Where is falsy is any variable that is a zero or empty.

Using the == you could compare pretty much any non-zero value (truthy) to true, and that would be a true statement. However if you used === it wouldn’t be a true statement.

Does that make sense?

1 Like

Sorry I am still confused.

1 Like

Yeah, it is confusing. Don’t worry about it! It will make sense down the track.
In the mean time just use == and !=, it will be fine. If you get bugs in your code you can’t figure out, it might be due to some of this stuff.

Day 5

Woo functions! This brings back vague memories of computing class… 14 years ago. I feel old saying that.

Starts off nice and simple:

function getReminder() {
console.log(“Water the plants.”);

function greetInSpanish() {
console.log(“Buenas Tardes.”);

Then has me calling functions:

function sayThanks() {
console.log(“Thank you for your purchase! We appreciate your business.”);

Parameters and arguments next:

function sayThanks(name) {
console.log('Thank you for your purchase ’ + name + ‘! We appreciate your business.’);


Default parameters:

function makeShoppingList(item1 = “milk”, item2 = “bread”, item3 = “eggs”){
console.log(Remember to buy ${item1});
console.log(Remember to buy ${item2});
console.log(Remember to buy ${item3});

Return! Not just a fancy name for the big enter key.

function monitorCount(rows, columns) {
return rows * columns;

const numOfMonitors = monitorCount(5, 4);


Helper functions:

function monitorCount(rows, columns) {
return rows * columns;

function costOfMonitors(rows, columns){
return monitorCount(rows, columns) * 200;

const totalCost = costOfMonitors(5, 4);


Function expressions:

const plantNeedsWater = function(day) {
if(day === “Wednesday”){
return true;
else {
return false;


I’m not sure I enjoyed function expressions as much as function declarations. Found it a bit trickier to get my head around.

Next arrow functions, like function expressions but minimally different?

const plantNeedsWater = (day) => {
if (day === ‘Wednesday’) {
return true;
} else {
return false;

Finish the day up with concise body arrow functions, turning this:

const plantNeedsWater = (day) => {
return day === ‘Wednesday’ ? true : false;

Into this:

const plantNeedsWater = day => day === ‘Wednesday’ ? true : false;

I think I found today a little bit easier than yesterday. I hope that’s the material sinking in and not just me feeling false confidence. I think it helps that I studied maths along with physics in the recent past so this feels tangentially familiar.


Day 6

Scope is being covered. This is where I assume the difference between var and let come in.

Blocks are the code between curly braces. The variable skyscraper is in the block but the variable city is not; making it a global variable.

const city = “New York City”;
function logCitySkyline() {
let skyscraper = “Empire State Building”;
return 'The stars over the ’ + skyscraper + ’ in ’ + city;


Using global variables in a block of code:

const satellite = “The Moon”;
const galaxy = “The Milky Way”;
const stars = “North Star”;

function callMyNightSky () {
return 'Night Sky: ’ + satellite + ', ’ + stars + ', and ’ + galaxy;


Demonstrating scope further; Reference error occurs when trying to console.log the value of lightWaves from outside the function. Works fine when calling the function:

function logVisibleLightWaves() {
const lightWaves = “Moonlight”



Scope pollution. Changing the value of global variables from inside a function as an example:

const satellite = ‘The Moon’;
const galaxy = ‘The Milky Way’;
let stars = ‘North Star’;

const callMyNightSky = () => {
stars = “Sirius”;
return 'Night Sky: ’ + satellite + ', ’ + stars + ', ’ + galaxy;


Logging the value of lightWaves from inside and outside a block of code to note the differences in output, demonstrating scope:

const logVisibleLightWaves = () => {
let lightWaves = ‘Moonlight’;
let region = ‘The Arctic’;
// Add if statement here:
if (region === “The Arctic”) {
let lightWaves = “Northern Lights”;


Today was super easy. I feel like a relatively simple concept was dragged over many tasks when it didn’t really need that many. It was a good lesson though and thinking about scope has me pondering more on the future of where my knowledge will go and structuring longer pieces of code.


Didn’t have time last night to report; catching up now.

Day 7

Arrays: Making lists and storing data. Here’s my first array, it’s very big:

const hobbies = [“Video games”, “Reading”, “Cooking”];

Arrays start at 0. I remember reading about this in memes or something on the internet. Accessing elements like so:

const famousSayings = [‘Fortune favors the brave.’, ‘A joke is a very serious thing.’, ‘Where there is love there is life.’];
const listItem = famousSayings[0];

Trying to access an index beyond the last element returns undefined.

Updating elements:

let groceryList = [‘bread’, ‘tomatoes’, ‘milk’];
groceryList[1] = “avocados”;

Let arrays vs const arrays:

let condiments = [‘Ketchup’, ‘Mustard’, ‘Soy Sauce’, ‘Sriracha’];

const utensils = [‘Fork’, ‘Knife’, ‘Chopsticks’, ‘Spork’];

condiments[0] = “Mayo”;

condiments = [“Mayo”];

utensils[3] = “Spoon”;

.length works for finding the number of elements in an array in the same way it finds characters in a string:

const objectives = [‘Learn a new languages’, ‘Read 52 books’, ‘Run a marathon’];

Using .push() to make arrays even bigger!

const chores = [‘wash dishes’, ‘do laundry’, ‘take out trash’];
chores.push(“cook dinner”, “go shopping”);

And .pop() to knock an element off the end.

const chores = [‘wash dishes’, ‘do laundry’, ‘take out trash’, ‘cook dinner’, ‘mop floor’];

More array methods:

const groceryList = [‘orange juice’, ‘bananas’, ‘coffee beans’, ‘brown rice’, ‘pasta’, ‘coconut oil’, ‘plantains’];



console.log(groceryList.slice(1, 4));

const pastaIndex = groceryList.indexOf(“pasta”);

Using functions with arrays:

const concept = [‘arrays’, ‘can’, ‘be’, ‘mutated’];

function changeArr(arr){
arr[3] = ‘MUTATED’;


function removeElement(newArr){


Finally, making a nested array!

const numberClusters = [[1, 2], [3, 4], [5, 6]];
const target = numberClusters[2][1];

I enjoyed this one. Learning about arrays was good, but combining my lessons on functions felt like I was making some good progress.


Here’s the code for how I’m connecting to my database. Thought you’d like to see it since you’re learning JS.

// connect to database
let db
let conn
(db = async () => {
  try {
    conn = await mariadb.createConnection(dburi)
  } catch (err) {
    console.log('not connected due to error: %s', err)
  if (conn) {
    console.log('database connected! connection id is %s', conn.threadId)

And here’s another fun one. A high-order function which takes a function as a parameter and returns a chained method to it. In this case, it is a .catch because I am using promises.

// Catch Errors HOF
// returns new function with chained .catch method
const catchErrors = (fn) => (req, res, next) => fn(req, res, next).catch(next)

The reason why this is useful, is because if I encounter an error, I will pass the object to next which will be picked up by a singular error handler. This allows me to centralize my error handling on my server and not have to have the same boilerplate error handling in every single route listener I have.

Picked that one up courtesy of Wes Bos. check the guy out he’s hella smart.

1 Like

Day 8

Loops today. Not the cereal, but the iterative functions.

Let’s repeat a task to gain an appreciation for how loops will help us in the future:

const vacationSpots = [“India”, “China”, “Japan”];

Lucky it only had me do 3 elements in that array.

Using for to count from 5 to 10:

for (let counter = 5; counter < 11; counter++){

Very concise!

Now to count down from 3 to 0:

for (let counter = 3; counter >= 0; counter–){

Looping through arrays:

const vacationSpots = [‘Bali’, ‘Paris’, ‘Tulum’];
for (let i = 0; i < vacationSpots.length; i++){
console.log("I would love to visit " + vacationSpots[i]);

Nested loops. Not sure I completely understood the syntax on this one but the program says I got it right?

const bobsFollowers = [“Alph”, “Beth”, “Casey”, “Dean”];
const tinasFollowers = [“Casey”, “Dean”, “Edgar”];
const mutualFollowers = [];

for (let i = 0; i < bobsFollowers.length; i++){
for (let j = 0; j < tinasFollowers.length; j++){
if (bobsFollowers[i] === tinasFollowers[j]){

The while loop. A wild while loop appears!

const cards = [‘diamond’, ‘spade’, ‘heart’, ‘club’];
let currentCard;

while (currentCard != “spade”){
currentCard = cards[Math.floor(Math.random() * 4)];


let cupsOfSugarNeeded = 10;
let cupsAdded = 0;

do {
console.log("Added cup of sugar number " + cupsAdded);
} while (cupsAdded < cupsOfSugarNeeded);

Break keyword:

const rapperArray = [“Lil’ Kim”, “Jay-Z”, “Notorious B.I.G.”, “Tupac”];

for (let i = 0; i < rapperArray.length; i++){
if (rapperArray[i] === “Notorious B.I.G.”){
console.log(“And if you don’t know, now you know.”);

I didn’t enjoy that last activity. All these functions, arrays and loops are too much for my head right now. I hope my head feels more fresh tomorrow and I can get a hang of this. My confidence is wavering a bit tonight.

I can kind of understand some of that but I do’t know try or catch yet.

Don’t forget to indent! (Apologies if you do and it didn’t translate into the post)

const bobsFollowers = [“Alph”, “Beth”, “Casey”, “Dean”];
const tinasFollowers = [“Casey”, “Dean”, “Edgar”];
const mutualFollowers = [];

for (let i = 0; i < bobsFollowers.length; i++){
	for (let j = 0; j < tinasFollowers.length; j++){
		if (bobsFollowers[i] === tinasFollowers[j]){

Also great work for going at it every day :clap:t3::clap:t3:


Yeah it indents automatically when I type it, just doesn’t translate in the copy - paste.

It would if you used spaces, instead of tabs.

_which is why spaces are superior

Why are you using Console.log? I’m just curious cause print() is less to type, and the user can see this as well.

The site I’m learning on hasn’t told me about print() yet, so it’s just been console.log() so far.

I feel like you aren’t being challenged, so want me to give a challenge?

The feeling of being challenged has been up and down throughout my learning, especially as this is now my day 9 of 1 hour per day. I don’t think I can take your challenge because I haven’t learnt how to take user inputs yet.

1 Like