Coding task · JavaScript and TypeScript course · Module 2: Functions, Arrays and Objects
Error Basics - Park Security System
throw stops the function and passes the error to the nearest catch, and finally always runs. The ?. operator returns undefined instead of throwing a TypeError, and ?? replaces only null and undefined, so 0 stays 0.
Task
Write a function findDinosaur(dinosaurs, id) that returns the dinosaur with the given id from the array and, when there is none, throws new Error('No dinosaur with ID ' + id). Write a function feedDinosaur(dinosaurs, id, food): in the try block find the dinosaur with findDinosaur, throw a TypeError when the food does not match the diet (carnivore eats 'meat', herbivore eats 'plants'), otherwise return true; in catch display error.message and return false; in finally display 'Closing the feeder'. Also write readVoltage(record) that safely reads record.sensors.voltage with the ?. operator and returns 'No sensor' when the value is missing (use ??).