Using Variables - Exercise

Contact Us or call 1-877-932-8228
Using Variables - Exercise

Using Variables

Duration: 5 to 15 minutes.

In this exercise, you will practice using variables.

  1. Open VariablesArraysOperators/Exercises/Variables.html for editing.
  2. Below the ADD PROMPT HERE comment, write code that will prompt the user for her first name and assign the result to a variable.
  3. Add a button below the Ringo button that reads "Your Name". Add functionality so that when this button is pressed an alert pops up showing the user's first name.
  4. Test your solution in a browser.

Code Sample:

VariablesArraysOperators/Exercises/Variables.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript Variables</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
	//ADD PROMPT HERE
</script>
</head>
<body>
<form>
	<input type="button" value="Paul" onclick="alert('Paul');">
	<input type="button" value="John" onclick="alert('John');">
	<input type="button" value="George" onclick="alert('George');">
	<input type="button" value="Ringo" onclick="alert('Ringo');">
	<!--ADD BUTTON HERE-->
</form>
</body>
</html>

Solution:

VariablesArraysOperators/Solutions/Variables.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript Variables</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
	var firstName = window.prompt("What's your name?", "");
</script>
</head>
<body>
<form>
	<input type="button" value="Paul" onclick="alert('Paul');">
	<input type="button" value="John" onclick="alert('John');">
	<input type="button" value="George" onclick="alert('George');">
	<input type="button" value="Ringo" onclick="alert('Ringo');">
	<input type="button" value="Your Name" onclick="alert(firstName);">
</form>
</body>
</html>
Next