typescript · level 1 · unit 2 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
lets your program ask a question.
prompt is like a waiter taking your order. It asks a question, waits while the person types an answer, then hands back what they typed as a string.
But what if nobody answers? Then prompt hands back , which means no value at all. So its type is string | null: a string, or null.
A string box cannot hold null. Add and a fallback, something to use instead. prompt("Snack?") ?? "nothing" gives the answer, or "nothing" when there is none.
let snack: string = prompt("Favourite snack?") ?? "nothing";
console.log("Yum, " + snack); Read ?? as “or, if there is no answer, use”.
guess first
Nobody answers. What appears?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
let name: string = prompt("What is your name?") ?? "friend";
console.log("Hello, " + name);
your turn
Your turn. Write the second question.
Write a question asking for a favourite food between the quotes on line 2. We will answer Sam and pancakes.
fix it
The checker will not let this run. Fix it!
- Read the error:
TS2322: Type 'string | null' is not assignable to type 'string'. promptmight hand backnull, and a string box cannot hold it. Give it a fallback.- Add ?? "pet" after the closing bracket of prompt on line 1, then press run.
nailed it
your program asked and listened. :D
promptasks a question and gives back the answer.- With no answer,
promptgivesnullinstead. ??swapsnullfor a fallback value.
new words in your collection
- prompt
- null
- ??
This lesson isn’t saved. A free account remembers every lesson you finish.