Quiz 01
-
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:
- The
city
field:
orconsole.log(data.location.city)
console.log(data["location"]["city"])
- All courses:
orconsole.log(data.courses)
console.log(data["courses"])
- The second course:
orconsole.log(data.courses[1])
console.log(data["courses"][1])
- The
-
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:
- The
id
field:
orconsole.log(data.user.id)
console.log(data["user"]["id"])
- The
preferences
field:
orconsole.log(data.user.profile.preferences)
console.log(data["user"]["profile"]["preferences"])
- The
language
field:
orconsole.log(data.user.profile.preferences.language)
console.log(data["user"]["profile"]["preferences"]["language"])
- The
-
Declare a function (using Function Declaration, Function Expression, and Arrow Function) named
greetings
that takes 2 parametersname
andfrom
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!
.-
Using Function Declaration:
function greetings(name, from) { return `Hello, ${name} from ${from}!` }
-
Using Function Expression:
const greetings = function (name, from) { return `Hello, ${name} from ${from}!` }
-
Using Arrow Function:
const greetings = (name, from) => { return `Hello, ${name} from ${from}!` }
or
const greetings = (name, from) => `Hello, ${name} from ${from}!`
-
-
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 } ]
- Using
fetch
with chainedthen
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
- Using
fetch
withasync/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()
- The