Javascript - Objects

Learning goals

  • What is an object

  • Accessing data using a key

  • Changing data using a key

  • Array of objects

Teacher instruction

  • Context for where in js we are

    • Basics

    • DOM

    • API

    • Visualisation

  • Divide your problem into smaller problems first

  • Opgave 6 kl 10:15

  • Opsamling kl 11:45

  • Feedback på portfolio opgave

    • Husk ul og li tags omkring liste af links

      <div class="left">
                  <a>
                      <img class="logo"
                           src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/62/TV_2_%282023%29.svg/1200px-TV_2_%282023%29.svg.png"
                           alt="tv2Logo">
                  </a>
                  <a>Nyheder</a>
                  <a>Sport</a>
                  <a>Vejr</a>
                  <a>TV</a>
              </div>
    • dividerForNews -> divider-for-news

    • Undgå fixed værdier:

      .NobelPicture {
          width: 40rem;
          height: 20rem;
    • Fedt at se at i tænker over variabel navne. Men tænk over variabelnavne. Hvad repræsentere de

      function getStartupName() {
      
          const firstWordRandom = Math.floor(Math.random() * firstWords.length);
          const secondWordsRandom = Math.floor(Math.random() * secondWords.length);
      
          const firstWordForCombine = firstWords [firstWordRandom];
          const secondWordForCombine = secondWords [secondWordsRandom];
      
          const startupName = `${firstWordForCombine} ${secondWordForCombine}`
          return `${startupName}`;
      }
    • whatLetterGrade(numberGrade) { - getLetterGrade

    • Pas på med at bruge reduce. I skal virkelig forstå den hvis i tilføjer den til koden! const getAverage = (studentGrades) => studentGrades.reduce((sum, currentValue) => sum + currentValue, 0) / studentGrades.length;

    • God brug af flex!

    • Del jeres kode op, så den er nemmere at forstå

      const first = firstWords[Math.floor(Math.random() * firstWords.length)];
    • Hvad kunne et bedre navn være:

      function rollDice() {
          // Generates a random number between 1 and 6
          return Math.floor(Math.random() * 6) + 1;
      }
    • Ting der er lister skal laves som en liste i html

      <!-- Videos -->
          <section class="videos">
      
              <div class="video">
                  <video height="225" width="400" controls
                         poster="https://i.ytimg.com/vi/hEHJuHlI7bA/hq720.jpg?sqp=-oaymwEnCNAFEJQDSFryq4qpAxkIARUAAIhCGAHYAQHiAQoIGBACGAY4AUAB&rs=AOn4CLCIxWvGbTu03AYIlJlrZvyxMlOfKw"
                         src="https://www.youtube.com/embed/il_hEHJuHlI7bA?autoplay=1&mute=1" class="video-one">
                  </video>
                  <div class="video-description">
                      <img height="40" width="40" src="images/wirual-logo.jpg" alt="Wirtual logo" class="wirtual-logo">
                      <div class="video-text">
                          <p class="caption">These Weekly Campaign Records are a Work of Art.</p>
                          <p class="creator">WirtualTV</p>
                      </div>
                  </div>
              </div>
      
              <div class="video">
                  <video height="225" width="400" controls
                         poster="https://i.ytimg.com/vi/hEHJuHlI7bA/hq720.jpg?sqp=-oaymwEnCNAFEJQDSFryq4qpAxkIARUAAIhCGAHYAQHiAQoIGBACGAY4AUAB&rs=AOn4CLCIxWvGbTu03AYIlJlrZvyxMlOfKw"
                         src="https://www.youtube.com/embed/il_hEHJuHlI7bA?autoplay=1&mute=1" class="video-one">
                  </video>
                  <div class="video-description">
                      <img height="40" width="40" src="images/wirual-logo.jpg" alt="Wirual logo" class="wirtual-logo">
                      <div class="video-text">
                          <p class="caption">These Weekly Campaign Records are a Work of Art.</p>
                          <p class="creator">WirtualTV</p>
                      </div>
                  </div>
              </div>
    • Hvad tror i den her betyder let numberOfT = 0;

    • Hvordan kan vi forbedre den her kode:

      
      //if statement to display how well the class has done based on their average grade
      if (getAverage(grades) >= 90) {
          console.log("Overall Class Performance: Excellent");
      } else if (getAverage(grades) >= 80 && getAverage(grades) <= 89) {
          console.log("Overall Class Performance: Good");
      } else if (getAverage(grades) >= 70 && getAverage(grades) <= 79) {
          console.log("Overall Class Performance: Satisfactory");
      } else if (getAverage(grades) < 70) {
          console.log("Overall Class Performance: Needs improvement");
      } else {
          console.log("ERROR");
      }
    • Snak om abstraktion mht skatten

    • Brug funktioner til at opdele jeres kode!

      // actual game function
      function PlayGame(){
          if (confirm("Do you want to start a dice tournament?")===false){
              return
          }
      
          let gameEnded = false
      
          amountOfPlayers = prompt("How many players? (max 8)")
          while (true){ // prompt proofing
              if (amountOfPlayers === ""){
                  amountOfPlayers = prompt("Error: please input a number!\nHow many players? (max 8)")
              } else if (isNaN(amountOfPlayers)){
                  amountOfPlayers = prompt("Error: please input a number!\nHow many players? (max 8)")
              }else if (amountOfPlayers>8){
                  amountOfPlayers = prompt("Error: no more than 8 players!\nHow many players? (max 8)")
              } else{
                  break
              }
          }
          for (let i = 0; i < amountOfPlayers; i++) {
              let playerName = prompt(`Player ${i+1} name: \n(leave blank for name: Player ${i+1})`)
              if (playerName === "") {
                  players.push([`Player ${i+1}`, [], 0])
              }else{
                  players.push([playerName, [], 0])
              }
          }
      
          if (confirm("Do you want to play standart settings?\n[best of 3 sets] of [10 rounds]\n\n(Press cancel to change settings)")===false){
              sets = prompt("How many sets?")
              rounds = prompt("How many rounds?")
              while (true){ // prompt proofing
                  if (isNaN(sets)){
                      sets = prompt("Error: please input a number!\nHow many sets?")
                  } else if (sets>10){
                      sets = prompt("Error: no more than 10 sets!\nHow many sets?")
                  }else if (isNaN(rounds)){
                      rounds = prompt("Error: please input a number!\nHow many rounds?")
                  }else if (rounds>20){
                      rounds = prompt("Error: no more than 20 rounds!\nHow many rounds?")
                  } else{
                      break
                  }
              }
          }
      
      
          // actual game loop
          for (let set = 1; set <= sets; set++) {
              for (let round = 1; round <= rounds; round++) {
                  let roundMessage = ""
                  if (sets > 1) {
                      roundMessage = `Set: ${set} (best of ${sets})\n`
                  }
                  roundMessage += `Round: ${round}/${rounds}\n`
      
                  for (const player of players) {
                      if (round === 1) {
                          player[1].push([])
                      }
                      let playerScore = 0
      
                      alert(roundMessage + `${player[0]}, press Enter to roll...`)
      
                      let roll = DiceRoll()
                      player[1][set - 1].push(roll)
      
                      // get players total score this set
                      for (const setScore of player[1][set - 1]) {
                          playerScore += setScore
                      }
      
                      let rollMessage = ""
                      if (sets > 1) { // show sets if more sets are played
                          rollMessage += `${player[0]} rolled: 🎲 ${roll} 🎲 (Total: ${playerScore}, Sets: ${player[2]})\n`
                      } else {
                          rollMessage += `${player[0]} rolled: 🎲 ${roll} 🎲 (Total: ${playerScore})\n`
                      }
                      roundMessage += rollMessage
                  }
      
                  if (round === rounds) { // if last round was played
                      alert(roundMessage + "\n-------------------------\n----- Set finished! -----\n-------------------------")
                  } else {
                      alert(roundMessage + "\n--- Round finished ---")
                  }
              }
      
              // 2 arrays: one which is sorted, and one that isn't, used to reference original player index
              const scoreboard = []
              let sortedScoreboard = []
      
              for (const player of players) {
                  let setTotal = 0
                  for (const setScores of player[1][set - 1]) {
                      setTotal += setScores
                  }
                  player[1][set - 1].push(setTotal)
                  scoreboard.push([player[0], setTotal])
                  sortedScoreboard.push([player[0], setTotal])
              }
      
              sortedScoreboard.sort((a, b) => b[1] - a[1]) // sort players by set total
      
              let winningIndex = 0
              // if top 2 players are tied, play sudden death
              if (sortedScoreboard[0][1] === sortedScoreboard[1][1]) {
                  let player1won = SuddenDeath([sortedScoreboard[0][0], sortedScoreboard[1][0]])
                  if (player1won === false) {
                      winningIndex = 1
                  }
              }
      
              // find which player is first to update their score.
              for (let i = 0; i < scoreboard.length; i++) {
                  if (scoreboard[i][0] === sortedScoreboard[winningIndex][0]) {
                      players[i][2] += 1
      
                      // if the winner has a lead to secure a ´best of x´ win, end tournament
                      if (players[i][2] > (sets / 2)) {
                          GameOver(true)
                          gameEnded = true
                          break
                      } else {
                          alert(`Set winner is: ${sortedScoreboard[winningIndex][0]}`)
                      }
                  }
              }
              if (gameEnded){
                  break
              }
          }
          if (gameEnded === false){
              GameOver() // end game after all sets are played
          }
      }
    • Hvad tror i en funktion der hedder trackScore gør?

    • brug a med tel til telefonnumre: Tlf: 77 77 77 29

Peer instruction 1 min

Question 1

What is the value of orResult?

  1. true

  2. false

  3. true&&false

  4. None of the above

Question 2

What will the following code log out?

  1. 43

  2. "43"

  3. "age"

  4. "User.age"

  5. Syntax error

Flipped classroom videos

What is an object?

What problem does obejcts solve?

Let's say we wanted to store the name, age and email of a user with what we have learned so far. We could fx create 3 variables to hold this information:

This would work but we would very quickly run into problems when we get more users. What if we had 1000 users, now we would need to create 3000 variables 😱. That would obviously not work.

What about storing this data (name, age and email) in an array. Let's try that:

This is a bit better but what if we forgot where we stored the different values. Let's say we have 30 things we want to store on a user. Was the favorite food stored in index 27 or 28? Or what if we forgot where we stored these things? Now we would have to create an extra array that keeps that of where we store what information

Hmm now we are creating extra work and extra confusion. What if there was a data structure where we save information using a the name what we are storing (key).

Well we are in luck 👇

Objects

In an object we instead use a key to refer to some data. Objects are a key-value pair that can store any data type, including other objects. They're used to store data about a single thing and are often used to store data about a user or a product. Let's solve the problem we outlined above:

Here we create a new object with 3 keys: name, age and email. What is smart is that it is easy to access the kind of data we are interested in.

Accessing data using key

Let's try and access some of the data form the user object

We can access data at a key using either dot notation of square brackets. This is the same: console.log(user.email) and console.log(user['email']).

Changing data using key

We are not only able to access data using key, but we can also change it.

Array of objects

When working with data in javascript it is often in the form of an array of objects. Take a look at this json filearrow-up-right that contain movie data. It is an array of objects. Let's take a closer look at it 🔎

Every object in the array represents a movie and has the following keys: title, year, rating, votes, running_times. If i wanted to get the second movies rating in javascript i would write

Exercises

📝 Exercise 1 - level 1

The objects below have some syntax issues - try and fix them all!

📝 Exercise 2 - level 1

Create an object that describes you. Fx a key called age with the value of 28. Add a key that holds an array. Add minimum 6 keys

📝 Exercise 3 - level 1

Log the values of each property of kitten

📝 Exercise 4 - level 1

Write code in the space provided so that the expected values output

Exercises taken from here: https://syllabus.codeyourfuture.io/js-core-2/week-1/lesson

📝 Exercise 5 - level 2

The following object represents all the people that are in space right now.

Data is taken from herearrow-up-right

Using the astronautsInSpace variable log out the following things

  1. The number of astronauts in space right now

  2. The name of the craft of the last person in the array

  3. The lastname of the first astronaut in the ISS

📝 Exercise 6 - Lets analyze this code in class

  • What does it do?

  • How do we communicate about code?

  • How should we improve it?

Rettet kode:

📝 Exercise 7 - Please improve the following code

8 - Build a sentiment analyzer

A sentiment analyzer is some functionality that figures out how positive/negative a sentence is.

Fx the sentence "I am mega super awesome happy" Should have a high score The sentence "I hate doing boring stuff" should have a low score.

Create a function that takes a string as a parameter. Calling the function will return an object with score, positiveWords and negativeWords. You decide how the score should be implemented and what words are negative and positive.

Here is an example of using the function:

9 - Character frequencies - optional

Write a function that counts the frequency of characters in a string:

10 - Credit card number formatter - optional

This is a very real world example of a problem i got at my previous work. I was tasked to implement one of the smart credit card input fields, where the credit card numbers are seperated with a space. Fx inputting 123456789 would show 1234 5678 9.

Credit card formatter

Create a function that takes a number as parameter. The function should return the following object:

Things to consider:

  • What should happen if the function is called with an argument that is not a number?

Algebraic notation chess svær opgave

Lav en funktion der kan tage imod en chess notation og vurdere om den er valid.

https://www.youtube.com/watch?v=iDnW0WiCqNc

https://www.chess.com/terms/chess-notation

Last updated