We’re going to make a small program that accepts a user’s name and writes out different sentences based on what they type.
This is what it should look like when it’s done:
Watch some videos showing basic JavaScript syntax and build a small name comparing program.
We’re going to make a small program that accepts a user’s name and writes out different sentences based on what they type.
This is what it should look like when it’s done:
Remember the purpose of this lesson is to type the code out yourself—build up that muscle memory in your fingers!
Start the lesson by forking and cloning the whats-yo-name
repository.
Fork & clone the “whats-yo-name” repo.
The repository will have some starter files to get you on your way and include requirements for Markbot so you can be sure you’ve completed the lesson.
This includes some starter code that you can get by forking and cloning the repository. You’ll use Markbot to double check everything is done properly.
Before we start writing any JavaScript we need to have an HTML file set up. That’s where we’ll start.
index.html
& add the boilerplate code.main.js
in your js
folder.Don’t forget to follow the naming conventions.
Create the boilerplate with html5
, viewport
At the bottom of the index.html
file we need to connect the JavaScript file.
⋮
</head>
<body>
<script src="js/main.js"></script>
</body>
</html>
JavaScript files are always connected at the bottom, right before the closing </body>
tag.
The <script>
tag is used to connect a JavaScript file to HTML.
It should always go at the bottom for two reasons:
These few lines of code will ask a user for their name and display a message based on what they type.
var newName = prompt('What is your name?');
if (newName == 'Thomas') {
alert('Names are the same!');
} else {
alert('Names are different.');
}
Try it out in your browser. It should work great.
The variable newName
will hold whatever someone types into the dialogue box.
The prompt()
is a function built into JavaScript that will display a dialogue people can type into.
The if-statement is going to compare the contents of newName
against the string 'Thomas'
.
The double equals ==
means compare.
A single equals =
means set.
The alert()
function is built into JavaScript and will display a dialogue with some text.
Change the program above so that the alert
messages say what the user typed in. Make the messages read:
You’ll have to combine strings and variables together with a special character.
Drop the final, coded exercise into Markbot and fix all the errors until Markbot gives you all green (and maybe a little yellow).
After you’ve fixed all the problems, go ahead and submit the assignment. You’ll immediately get your grade.