> alert("Hello world!");
When we press enter, the page pops open a dialog box that says "Hello world!"
alert() is a function. A function is something that performs an action. Just like a method, a function can take an argument. The
alert() function pops up a dialog box with the string that you pass in as an argument.
> prompt("What is the air-speed velocity of an unladen swallow?"); // I'm going to type "African or European?" "African or European?"
This dialog box lets you type in a response, and then that response is returned from the
prompt() function. One cool thing we can do here is set a variable equal to the response, like this:
> const favoriteColor = prompt("What is your favorite color?"); // I'm going to type "green" undefined > favoriteColor; "green"
Here we created a variable named favoriteColor and assigned it to hold the string inputted by the user.
Just like we could chain methods to each other, we can also chain methods to a function:
> prompt("Type something in lowercase:").toUpperCase(); // I'm going to type "cat" "CAT"
Another built-in function that allows us to interact with the webpage user is the
confirm() function. This too takes a string as an argument.
> confirm("Are you sure?"); // I'm going to press the OK button true
confirm() returns one of two values:
false. Notice that there are no quotes around these values. That is because these are booleans, not strings. They simply represent being true or false. You saw them before when you worked with comparison operators.
And on that note, you might have noticed that
undefined, also without quotes.
undefined simply represents that nothing has been returned from the function, or, as you saw earlier, that a variable hasn't been assigned a value.
It is good to be conscious of what arguments a function takes, and what data type it returns. Here is a table showing that information for the three built-in functions introduced in this lesson:
alert() function does not return anything useful, which is fine because we'd only use it to display some information to the user. It's a way to output information, not collect it. On the other hand, we'd want to collect the user's response to the
confirm() functions, likely by assigning the returned value to a variable as demonstrated above with
const favoriteColor = prompt("What is your favorite color?");. That way we can do something with the inputted information rather than just ignoring it.
Function: A function is a block of code that performs an action and returns a result; optionally takes arguments
Comment: anything following
alert() opens a dialog box and returns
confirm() opens a dialog box and returns a boolean.
prompt() opens a dialog box and returns a string.
Lesson 20 of 27
Last updated April 7, 2021