My Experience with Codecademy's "Learn JavaScript" course

arupv

AruPV

Posted on July 9, 2022

My Experience with Codecademy's "Learn JavaScript" course

So I just finished Codeacademy's beginner level Javascript course (Hooray!). I had a lot of fun with it and thought it might be a good idea to go through what I learned there both because I want to review some stuff I was a tad bit iffy on still and because I want to get into the habit of journaling a bit more (this counts as journaling, right?).

And I guess maybe someone who, like me, is learning JavaScript might find this useful too!

I'll go through each of the sections (units?) of the course, give a general description, a quick "cheat-sheet" of concepts.

I did get the "pro" version of Codecademy (which is somewhat affordable with a student discount), so I'll be talking about the bite-sized "projects" they have you do while you're taking the main course also


Introduction

This one is actually the second unit of the course, but the first one is just a small article (they call them "informationals") welcoming you to the course.

The first part of the course introduces us to comments, the console.log() method, fundamental data-types, dot notation, and the Math object.

//I'm a single-line Javascript comment!

/*
And I'm a multi-line Javascript comment!
*/
Enter fullscreen mode Exit fullscreen mode

The console.log() method is self-explanatory. It logs _things onto your _console.

console.log("Like this!")
Enter fullscreen mode Exit fullscreen mode

And the Math object allows us to performs all kinds of operations on numbers, like:


//Round down
Math.floor(x)

//Round up
Math.ceiling(x)

//Trig
Math.sin(x)
Math.tan(x)
Math.cos(x)

Enter fullscreen mode Exit fullscreen mode

The second part of the unit introduces us to variable. Javascript seems to have a couple of different keywords one can use to create variables: "var," "let," and "const." The keyword "const" gives you a static variable, while the keyword "let" allows for dynamic variables (not really sure when we're supposed to use the "var" keyword, but whatever).

//Use let to define a dynamic variable
let changeMe

//Use const to define a static variable
const doNotChangeMe
Enter fullscreen mode Exit fullscreen mode

Another cool thing about JS is the ability to use template literals (woah!). Obsessed with these at the moment.

let favoriteFood = "Mapo Tofu"
console.log(`I wish I was eating ${favoriteFood} rn.`)
Enter fullscreen mode Exit fullscreen mode

The Pro-jects

The projects for this unit were relatively simple, I think. We were tasked with making a little program that converted degrees in Kelvin to celsius and farenheit.

//kelvin is the forecast for today
const kelvin = 0
//celsius is kelvin -273
let celsius = kelvin - 273
//farenheit calculations
let farenheit = celsius * (9/5) + 32
//round down farenheit number
farenheit = Math.floor(farenheit)
console.log(`The temperature is ${farenheit} degrees Farenheit.`)
Enter fullscreen mode Exit fullscreen mode

And a similar one to convert human years to dog years.

const myAge = 21
//first two years of a dogs life counts as 10.5 dog years
let earlyYears = 2
earlyYears *= 10.5
//first two years from my age
let laterYears = myAge - 2
//make laterYears into dog years
laterYears *= 4
//sum both later and young years
let myAgeInDogYears = laterYears + earlyYears
//save my name turn it to lowercase
const myName = "Aru".toLowerCase() 
//print it all out
console.log(`My name is ${myName}, I am ${myAge} years old in human years and ${myAgeInDogYears} years old in dog years.`)
Enter fullscreen mode Exit fullscreen mode

But generally speaking, this was a relatively short unit that is meant to serve as a foundation for the rest of the course!

Conditionals

After that we have a section on conditionals. Coming from a background in analytic philosophy computational logic makes me feel right at home!

We went over a couple of things: comparison operators, if statements and "truthy and falsy" values.

Comparison operators seem really standard, you have your >s, and <s, the <= and >=, and (this threw me for a bit of a loop) === for identity relations (isn't it often two equal signs?).

if and else if statements are really straight forward also.

let something = true
let someOtherThing = false

if (something){
   return 'do the first thing'
} else if (someOtherThing){
   return 'do the second thing'
} else {
   return 'do the the third thing'
}
Enter fullscreen mode Exit fullscreen mode

You can also write conditionals as ternary expressions. Which shortens them by a couple of keystrokes.

something ? return 'do the first thing'
Enter fullscreen mode Exit fullscreen mode

Javascript also allows for switch statements, which instead let you do something like

let something = 'peanut'

switch (something){
   case 'apple':
     return "I like!"
     break;
   case 'peanut':
     return "I like!"
     break;
   case 'eggplant':
     return "I'm so sorry, I should have said this before you started making dinner, but I'm actually allergic to eggplant. No omg it's okay don't worry about it I'll just get something on the way home. No please I promise I'm fine I wasn't too hungry anyways."
     break;
}
Enter fullscreen mode Exit fullscreen mode

Still somewhat confused about the whole "truthy" and "falsy" thing. I think it means that you can evaluate non-boolean data types as if they were. That empty strings and 0s will evaluate to false, and that most other things will evaluate to true.

The Pro-jects

Projects started to get a little more complex here, but nothing too crazy yet. We were tasked with making a little magic 8-ball that you would ask a question to and get a response to in return.

//get user's name
let userName = ''
//get user's question
let userQuestion = 'Will I get a million dollars today?'
//if username then non-generic, otherwise generic welcome
userName ? console.log(`Hello ${userName}!`) : console.log("Hello!")
//print what the user asked for, options for generic and non-generic
userName ? console.log(`So, ${userName}, you want to know "${userQuestion}"`) : console.log(`So, you want to know "${userQuestion}"`)
//get a random number to determine the outcome 
let randomNumber = Math.floor(Math.random() * 8)
//define eightball with global scope so its accessible outside the switch statement
let eightBall = ""
//switch statement depending on the random number for different responses
switch(randomNumber) {
  case 0:
    eightBall = "It is certain"
    break;
  case 1:
    eightBall = "It is certain-ish"
    break;
  case 2:
    eightBall = "hmm idk ask me again"
    break;
  case 3:
    eightBall = "i dont care"
    break;
  case 4:
    eightBall = "woah!"
    break;
  case 5:
    eightBall = "Maybe tomorrow? You should probably ask again tomorrow"
    break;
  case 6:
    eightBall = "That's actually so rude of you to ask. No"
    break;
  case 7:
    eightBall = "Yeah! probably!"
    break;
}
console.log(eightBall)
Enter fullscreen mode Exit fullscreen mode

Functions

Next up was a section about functions, and it seems like there are generally two ways one can go about defining them.

There is the common function declaration that looks pretty similar to most other languages I've perused through in the past.

function imAFunction (firstParam, secondParam){
   return firstParam + secondParam
}
Enter fullscreen mode Exit fullscreen mode

But there are also "arrow" functions that have slightly different syntax but seem to do just about the same things

const imAFunction = (firstParam, secondParam) => {
   return firstParam + secondParam
}
Enter fullscreen mode Exit fullscreen mode

Arrow functions can also be written concisely like this

 const imAFunction = (firstParam, secondParam) => firstParam + secondParam
Enter fullscreen mode Exit fullscreen mode

I'm not quite sure which one is best to use when, but I'm under the impression the safe bet is to use arrow functions when possible, so that's what I've been doing.

The Pro-jects

This project was kind more fun than the past two! I was tasked with making a rock, paper, scissors game that took one input and played it against a computer.

//A function that gets a user input and checks its validity, makes it lowercase 
const getUserChoice = userInput => {
  userInput = userInput.toLowerCase();
  if (userInput == 'rock' || userInput == 'paper' || userInput == "scissors"){
    return userInput;
  }else {
    console.log("Error!");
  }
};

// A function that picks between rock, paper, and scissors randomly for the opponent
function getComputerChoice(){
  let choiceNumber = Math.floor(Math.random()*3);
  switch(choiceNumber){
    case 0:
      return 'rock';
      break;
    case 1:
      return 'paper';
      break;
    case 2:
      return 'scissors';
      break;
  }
}

// A function that plays the game out!
function determineWinner(userChoice, computerChoice){
  // If both are same, its a tie
  if(userChoice == computerChoice){
    console.log(`It's a tie! ${userChoice}`);
  // Now the options for user picking rock
  } else if (userChoice == 'rock'){
    // User picked rock, computer picked paper. Computer wins
    if(computerChoice == 'paper'){
      console.log("Computer wins! Paper beats rock")
    // User picked rock, computer picked scissors. User wins
    } else {
      console.log("You win! rock beats scissors")
    }
  // Now the options for user picking paper
  } else if (userChoice == 'paper'){
    // User picked paper, computer picked rock. User wins  
    if(computerChoice == 'rock'){
      console.log("You win! Paper beats rock")
    // User picked paper, computer picked scissors. Computer wins  
    } else {
      console.log("Computer wins! scissors beats paper")
    }
  // Now the options for user picking scissors
  } else {
     // User picked scissors, computer picked rock. Computer wins
     if(computerChoice == 'rock'){
      console.log("Computer wins! rock beats scissors")
    // User picked scissors, computer picked paper. User wins
    } else {
      console.log("you win! scissors beats paper")
    }
  }

}
computerChoice = getComputerChoice();
console.log(computerChoice);
console.log(determineWinner(getUserChoice("Paper"),
Enter fullscreen mode Exit fullscreen mode

Scope

So, Scope. This was a rather short lesson that went over best practices for scoping in Javascript. My main takeaway from it was that you cant access local variables from outside their block, but that you should still try to narrow down the scope of variables so you don't create a lot of scope pollution.

I don't think I will post the project I made here because it really was pretty small and consisted mostly of fixing the scoping of code provided by codeacademy. Definitely an important lesson (just maybe not the most exciting one)!

Arrays

I really enjoyed the arrays unit! There was a ton of information on array methods and I'm not quite sure I remember all of it, but generally speaking we went over the following.

Arrays are defined in much the same way they tend to be defined, with square brackets, with the first item in the array having an index of 0.

let myArray= ['First Item', ' Second Item', ' Third item']
return myArray[0] //returns 'First Item'
Enter fullscreen mode Exit fullscreen mode

You have functions that allow you to really easily implement stacks with arrays:

.push(): Add items to the end of an array
.pop (): Delete item from the end of an array

You also have the "shift" function if you want to implement queues.

.shift(): Delete item from the beginning of an array

and the un-shift function, which is the inverse of the shift function

.unshift(): Add item to the beginning of an array

let myArray= ['First Item', ' Second Item', ' Third item']
//Add element to the end of the array
myArray.push('Fourth item') //['First Item', ' Second Item', 'Third item', 'Fourth item']
//Delete element from the end of the array
myArray.pop() //['First Item', ' Second Item', ' Third item']

//Delete element from the beginning of the array
myArray.shift() //[' Second Item', ' Third item']

//Add element to the beginning of the array
myArray.unshift('New First Item') //['New First Item', ' Second Item', ' Third item']
Enter fullscreen mode Exit fullscreen mode

Another couple of useful methods that arrays have are:

.splice(x,y): Removes an item from array at a given index. x is the index of first item to be deleted and y (optional) the amount of total items (including the one at index x) that will be deleted.

.join(x): Merge the elements of the array, outputs a string. You can provide a string in "x" (optional) that will be placed between elements of the array, by default this is commas.

.indexOf(x): Finds the first element in the array with value "x"

let myArray= [1, 2, 3, 4, 5, 6, 7]
myArray.splice(1,2) // [1, 4, 5, 6, 7]
myArray.indexOf(4) // returns 1
myArray.join() // returns "1,4,5,6,7"
Enter fullscreen mode Exit fullscreen mode

There's a ton more! I think I'll be using this documentation as a resource moving forward

Pro-jects

There was one project for the arrays unit; it tasked me with "decipher" a secret message in an array. The only thing I had to do was perform the several methods I outlined previously so I won't post it here.

Loops

Loops! We went through three different kinds of loops here: for loops, while loops, do while loops.

For loops are the easiest in my opinion, you give it a counter and it performs an operation a certain amount of times.

for (i = 0; i < 10; i++){
  //do the thing
}
Enter fullscreen mode Exit fullscreen mode

You can also do for loops through an array

let myArray  = ['a', 'b', 'c']
for (const letter in myArray){
  return `The letter ${letter} is in this array'
}
Enter fullscreen mode Exit fullscreen mode

I'm not entirely sure of the difference between a while loop and a do..while loop, but I think it's that a do..while loop will always run at least once because of its conditions being evaluated at the end of the loop, but a while loop will not do so unless the conditions are met at the beginning of the loop.

// This will not run
let i = 10
while (i < 10){
   i *= 10
}

// But this one will
do {
 i *= 10
} while (i < 10)
Enter fullscreen mode Exit fullscreen mode

Pro-jects

This project was a lot of fun actually! I had to make a string into "whalespeech" (only vowels, O's and U's get repeated). I went about it like this

//Input for whale-ification
let input = " War. War never changes. The end of the world occurred pretty much as we had predicted. Too many humans, not enough space or resources to go around. The details are trivial and pointless, the reasons, as always, purely human ones";
//These are the vowels in the english language
const vowels = ['a','e','i','o','u'];
//array that will contain whalespeech
let resultArray = [];
//iterate through the input string
for ( i = 0 ; i < input.length ; i++ ){
  //iterate through the vowels array
  for ( c = 0 ; c < vowels.length ; c++ ){
    //if the character in position i in the string is a vowel, then run this block of code
    if (input.charAt(i) == vowels[c]){
      let toArray = input.charAt(i);
      //add the character to the output array
      resultArray.push(toArray);
      //if its an o or u then add it again
      if (toArray == 'o' || toArray == 'u'){
              resultArray.push(toArray);
      }
    }
  }
}

let resultString = resultArray.join("").toUpperCase();
console.log(resultString) // AAEEAEEEOOEOOOOUUEEUUAEAEIEOOOOAUUAOOEOOUUAEOOEOOUUEOOOOAOOUUEEAIAEIIAAOOIEEEAOOAAAUUEUUAOOE
Enter fullscreen mode Exit fullscreen mode

Iterators

Another short lesson, it goes through a couple more array methods:

.forEach(): executes the same code on each element of an array. Does not change the array and returns undefined

.map(): executes the same code on each element of an array. Does not change the array and returns a new array

.filter(): returns an array with the elements that meet a condition

.reduce(): operates on all elements of an array, returns a single value.

Objects

The last unit of the course (finally!). Thank you for getting this far! This unit (as the name suggests) introduces you to the concepts of objects and methods.

Objects have a really simple syntax in JS

let myObject = {
  //properties of the object
  name: 'My First Object',
}
Enter fullscreen mode Exit fullscreen mode

You can nest objects in objects as such

let myCar = {
  //properties of the object
  name: 'My First Car',
  passengers: {
    driver: {
      name: 'Vaquita Jose',
      age: 3
  }
}
Enter fullscreen mode Exit fullscreen mode

And you can make objects have methods by writing them like a funnction

let myCar = {
  //properties of the object
  name: 'My First Car',
  passengers: {
    driver: {
      name: 'Vaquita Jose',
      age: 3
  },
  startUp (){ return 'Vroom Vroom' }
}
Enter fullscreen mode Exit fullscreen mode

Some particularly important functions are setters and getters. Setters allow you to safely change information in an object, while getters do the same for getting information from an object

let myCar = {
  //properties of the object
  _name: 'My First Car',
  passengers: {
    driver: {
      name: 'Vaquita Jose',
      age: 3
  },
  startUp (){ return 'Vroom Vroom' },
  get name() { return this._name },
  set name(newName) { this._name = newName }
}
Enter fullscreen mode Exit fullscreen mode

And finally, there's the factory functions that allow us to quickly build objects

   let robotFactory = (model, mobile) => {
  return{
    model: model,
    mobile: mobile,
    beep(){
      console.log('Beep Boop')
    }
  }
};
Enter fullscreen mode Exit fullscreen mode

Pro-jects

The project for this lesson required me to put it all together and create a menu!

const menu = {
  _meal: '',
  _price: 0,
  //setter methods
  set mealToCheck(meal) {
    if (typeof meal == 'string'){
      this._meal = meal;
    };
  },
  set priceToCheck(price){
    if (typeof price == 'number'){
      this._price = price;
    };
  },
  //getter methods
  get todaysSpecial (){
    if ((this._meal == true) && (this._price == true)){
      return `Today's special is ${this._meal} for ${this._price}!`
    } else {
      console.log(this._meal == true)
      console.log('Meal or price was not set correctly');
    }
  }
};

menu.priceToCheck = 10;
menu.mealToCheck = 'pasta con caraotas';

console.log(menu)

console.log(menu.todaysSpecial)
Enter fullscreen mode Exit fullscreen mode

Closing Thoughts

I think this course was a really fun experience and a great way to get me started on my Javascript journey! I'm sorry for the rather long post, but I think there was a fair amount to cover. I hope to post a big more about my own projects soon.

Thank you for reading !
Aru

💖 💪 🙅 🚩
arupv
AruPV

Posted on July 9, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related