Message Boxes, Comments, and Type Conversion Flashcards
alert,
An alert box is used to give information to the user. The user will be asked to click “OK” to proceed.
window.alert(“The program is ready to begin.”);
confirm,
var userResponse = window.confirm(“Are you ready?”);
if (userResponse === true)
{
document.write(“You pressed OK.”);
}
else
{
document.write(“You pressed Cancel.”);
}
prompt
A prompt box is used to allow the user to input a value. After entering the value, the user must click on “OK”
or “Cancel”. If the user clicks “OK”, the input value is returned; if the user clicks “Cancel”, a null value is
returned.
var userValue = window.prompt(“Enter your name:”);
if (userValue != null)
{
document.write(“Welcome “ + userValue);
}
comments
code. Comments will not be
read by the computer as commands but can remind you of what you were doing or document for others
how your code works. In Javascript, any line beginning with double forward slashes (//) will be ignored by
the computer as a comment.
// This section of code will ask for the user’s name.
convert a string into a number
There are
different ways to do this, but I would suggest you use the Number() method, which takes in a string and
returns a number.
var num1 = Number(window.prompt(“Enter a number:”));
convert a number into a string
There is a similar method to convert from strings to numbers: String(). This takes in a number and returns a
string.
var string1 = String(num1);
check if a variable is a sting or not
If you are not sure of a variable’s type and want to check, you can use the typeof operator, which returns
the datatype. For example, the following instruction will display the datatype of the variable num1:
document.write(typeof num1);