Quiz 01

  1. Given the following JSON object and assuming it’s stored in a variable named data:

    { "name": "John Doe", "age": 30, "location": { "city": "Calgary", "country": "Canada" }, "courses": [ "comp3512", "comp1633" ] }

    Write code to log to the console:

    1. The city field:
      console.log(data.location.city)
      or
      console.log(data["location"]["city"])
    2. All courses:
      console.log(data.courses)
      or
      console.log(data["courses"])
    3. The second course:
      console.log(data.courses[1])
      or
      console.log(data["courses"][1])

  1. Given the following JSON object and assuming it’s stored in a variable named data:

    { "user": { "id": 12345, "profile": { "name": "Alice", "preferences": { "theme": "dark", "language": "en" } } } }

    Write code to log to the console:

    1. The id field:
      console.log(data.user.id)
      or
      console.log(data["user"]["id"])
    2. The preferences field:
      console.log(data.user.profile.preferences)
      or
      console.log(data["user"]["profile"]["preferences"])
    3. The language field:
      console.log(data.user.profile.preferences.language)
      or
      console.log(data["user"]["profile"]["preferences"]["language"])

  1. Declare a function (using Function Declaration, Function Expression, and Arrow Function) named greetings that takes 2 parameters name and from and using Template Strings, returns a string in this format: Hello, <name> from <from>!. For example, if name is "Alice" and from is "Calgary", the function should return: Hello, Alice from Calgary!.

    1. Using Function Declaration:

      function greetings(name, from) { return `Hello, ${name} from ${from}!` }
    2. Using Function Expression:

      const greetings = function (name, from) { return `Hello, ${name} from ${from}!` }
    3. Using Arrow Function:

      const greetings = (name, from) => { return `Hello, ${name} from ${from}!` }

      or

      const greetings = (name, from) => `Hello, ${name} from ${from}!`

  1. Write JavaScript code that using fetch gets information from this API (https://api.thecatapi.com/v1/images/search) and logs to the console:

    • The url field
    • The id field

    Assume the output of the API has the following structure:

    [ { "id": "lClcFEjwx", "url": "https://cdn2.thecatapi.com/images/lClcFEjwx.jpg", "width": 1584, "height": 1000 } ]
    1. Using fetch with chained then functions:
      fetch("https://api.thecatapi.com/v1/images/search") .then(res => res.json()) .then(data => { console.log(data[0].url, data[0].id) }) .catch(console.error); // this line's optional
    2. Using fetch with async/await:
      const getData = async () => { const res = await fetch("https://api.thecatapi.com/v1/images/search") const data = await res.json() console.log(data[0].url, data[0].id) } getData()