JavaScript
Today we're going to be writing a validation script. It's going to check if a person(under the premise that they're being honest) is old enough to enter a website. It's about 8 lines of code, but it really shows how much you can do with just 8 lines of code in .js. We start off with this:
var userAge = parseInt(prompt());
Notice the new word: parseInt; it's a fairly obvious term. The variable <userAge> returns a string, so rather than setting userAge equal to the prompt, you put a function around the prompt that will return the value that prompt() gets from the user into a number, and that means you parse an integer with <parseInt>! pretty nifty, eh? I thought so.
Next up we have this:
if(isNaN(userAge)){
console.log("Not a number,bro.");
}
It's checking to see if the response wasn't a number. ParseInt can only turn a string into a number if it is a number, obviously. So, you make an <if/else> that makes sure that the person entered what was wanted. This is a good practice for pretty much anything ever when it comes to this kind of thing.
You should also notice the use of <isNaN>. isNaN stands for is not a number. Like many things in .js there are tons of these little words that are so useful, and this is definitely one of them. So, next time you need to have something that checks if something is returning a number, it's <isNaN> to the rescue! You just stick your parameter in there, userAge in this case, and it's good to go.
The next step is a simple < else if/else> setup:
else if(userAge<18){
console.log("You're not allowed in here, young whippersnapper!");
}else{
console.log("Come on in!");
}
That pretty much explains itself, so here's the whole script:
var userAge = parseInt(prompt("Do you even do age, bro?"));
if(isNaN(userAge)){
console.log("Not a number,bro.");
}else if(userAge<18){
console.log("You're not allowed in here, young whippersnapper!");
}else{
console.log("Come on in!");
}
That should be enough info to take in for now. I hope y'all have an amazing weekend, I'll see you on Monday! It might be a late post, it's possible I'll have a million things to do. See y'all!
No comments:
Post a Comment