The second document continues the first one, further discussing concepts in JavaScript programming
This is a work in progress.
By now, you have learned how to store values and process them. All this may come to use only when you know how to take user input. The user input is actually mostly done with the HTML, but since you haven't reached that level yet, a more basic and easier way of taking it is the prompt
function.
The prompt function provides an input field to enter text. It needs one value, which is the text that should appear above the text input field. Here's how it runs:
var inputFromUser = prompt("What is your name?");
This will show an alert box like this:
And anything entered in the text field will be stored in the variable inputFromUser
.
With the above information, you should be able to get input from the user just fine. But here are a few things to to remember:
alert
undefined
is given as user input. To prevent undefined
from interfering with our work, we will need to check it using if
statements, which you will learn below.prompt
functions only returns (gives out) a string, even when a number is inputted. So, for this purpose, you will need to convert the number into a string form before performing arithmatic on it.prompt
without converting it into a number form first?
As stated above, the value obtained from the prompt
function is always a string. Meaning that performing arithmatic with this value (aiming for making a simple calculator) can be a bit of a problem. To convert the string value obtained from it into a number, we use the parseInt
function. It's functionality is demonstrated below in the Type Conversion section.
confirm
function:The confirm
function, as part of the family of these alert box functions, opens up a confirmation dialog. This can be used to obtain a "Yes or no" input from the user, or, speaking programatically, getting a true
or false
value from the user. It's usage is similar to the other two alert
and prompt
functions:
var isDocumentEasy = confirm("Is this document easy to understand?");
This will show an alert box like this:
The alert box presented by the confirm
function has two buttons, OK and Cancel. When the OK button is pressed, a true
value is received. And similarly, the Cancel button returns (gives out) a false
value.
Trying to escape the alert box by pressing Esc
also returns (gives out) a false
value.
You've seen that we are only allowed to modify the alert box description, and nothing else. That's because the alert box is supposed to be providing a very basic functionality for user interaction. Also, allowing developers to edit this very trustable looking alert box would allow them to make malicious alerts looking trusted. Let's say your grandma is browsing the web, and this alert box opens up saying "Chrome Update Available" "A new version of chrome is ready to install" with buttons text saying "Install now" and "Delete Everything and Install Virus". Now yes this alert box does feel absolutely dumb like why do I need to exit chrome if I can't update now, but for some inexperienced users, this may be looking like a regular software update, and they might fall for it. This also answers the question that why is the title of the alert box not editable.
If you want to have a better alert box with more buttons, better colors and more, then you'll have to make it yourself using HTML, and running JS behind to make it functional.
Here's a stackoverflow link to help understand it better.
By now, you know that there are strings and numbers in JavaScript:
var items = "5"; // This is a string, different from
var items = 5; // This, which is a number
Meaning that a number functions differently with operators (like the + sign). This is mostly fine, but the problem appears when you have to add a string, which contains a number digit, such that:
var firstNum = "5";
var secondNum = "10";
console.log(firstNum + secondNum); // Prints "510" instead of 15
Trying to add these together will simply make then join with each other, because they are strings, and strings are concatenated when the plus operator is used. So is it programatically impossible to add these numbers inside the strings?
No obviously, but the point is to tell the solution. It's rather easy, and is really useful when working with these sort of values:
parseInt(string)
Where string
is the string that needs to be converted.
The parseInt()
function takes in the string to convert as one argument (or input), and it returns (gives out) the converted numeric value. Remember that any returned value can be supplied to anything, whether it's a console.log
, alert
, or just storing the value in a variable.
var myFavouriteNumber = "7";
// How do we convert it to a number?
parseInt(myFavouriteNumber); // Returns a numeric value 7
// We can store it in a variable:
var myFavouriteActuallyNumber = parseInt(myFavouriteNumber);
// Now myFavouriteActuallyNumber contains the number 7
// We can print out the converted number without storing it too:
console.log("My Favourite number in a number form:", parseInt(myFavouriteNumber));
As observed above, I used commas ,
to separate the two values. This doesn't act as a concatenation operator at all, but it's just a functionality of the console.log()
function alone, that it can accept multiple arguments (inputs) and print the output separately in the same line.
The comma ,
causes each of the values to print out separately, and not get concatenated with each other. This way, you will be able to see the myFavouriteActuallyNumber
value show up in purple, indicating that its a number. If the plus +
operator was used instead, the value would have merged (concatenated) into the string before it, and the difference would not be signified.
You can successfully input a number through the above functions you learned. Combine the knowledge together and build a simple addition calculator, which inputs two numbers (through prompt
function), converts both of them to numeric values (suitable for arithmatic) (using the prompt
function), and alerts out their sum (using the alert
function)
Use variables to store the values obtained from prompt
, or from the conversion, however you are suitable with.
The above task to do can be done in a single line too! Can you think of a way to do it?
Don't store values in variables :)
By now, all you know about is to print, input and store values. But sometimes you need to have a decision in your program. You need to use logic, to specify certain instructions. Remember logic gates? Well, if
statements are a logical application of it in programming.
They're an fundamental concept, and exist in every programming language in some sort of way (not HTML, HTML is just a joke). They are abundently used in programming, and are really simple and helpful. In JavaScript, they are represented like this:
if (condition) {
// if body (the condition was matched)
}
// Or a more compact form:
if (condition) /* if body, cannot exceed more than one line */
// If you didn't understand the second form quite well, then it's entirely safe to ignore it entirely.
Where condition
can be any expression returning a value.
var isDocumentEasy = true;
if (isDocumentEasy) { // This condition should match, since the isDocumentEasy variable is true
console.log("This document is easy :)")
}
Symbolically speaking, the code inside the if
statement is only executed, if the condition
evaluates to true
. The reason I used the word "evaluates" is because the condition doesn't need to be exactly a true
boolean value, but anything that is taken as a true in boolean programming. Here's a generic list of values that should evaluate to specific boolean values:
true
. All boolean values obviously evaluate to their own value.
"Hello" // true
123 // true
[1, 2, 3] // true (this is an array, which you will learn about later)
0
evaluates to false
. This can be overridden by using strict comparisons, which are discussed down below.
""
) evaluate to false.
undefined
, null
, NaN
(excluding Infinity
) evaluate to false.
var aZeroNumber = 0;
var anEmptyString = "";
var aBooleanValue = true;
if (aZeroNumber) {
console.log("Condition Matched"); // This will not run.
}
if (anEmptyString) {
console.log("Condition Matched"); // This will also not run.
}
if (aBooleanValue) {
console.log("Condition Matched"); // This will run.
}
Try typing the above three if conditions without using the {}
brackets, as mentioned above as "compact form".
From above, you can see how giving values to the if
statements is done. If you want to perform a check in your code, you can do it in this way:
var isDocumentEasy = confirm("Is the document easy?");
if (isDocumentEasy) {
alert("That's cool!");
}
Obviously, you can directly supply values as well:
if (confirm("Is the document easy?")) {
alert("That's cool!");
}
else
block:You have observed that you can conditionally run specific blocks of code if the value is true
just fine, but what if you need to run the code if it's false
? Or what if you want to run something else if the if
doesn't match?
Here comes the else
block. The else
block is closely related to the if
blocks, and it is bound to be only used with an already present if
block. Since the if
block runs it's code when the condition is true
, the else
block runs it's code when the if
condition isn't matched.
var isDocumentEasy = confirm("Is the document easy?");
if (isDocumentEasy) {
alert("That's cool!");
} else {
alert("You can try to read less of this document at a time, and focus on concepts more strongly. This can help making this document feel easy.");
}
The above condition block is now complete. You can run it to see some results :D
The else
block makes things a bit more complicated, and is relatively harder to understand. Here are a few points to keep in mind about this:
else
block always comes after the if
block, after the brackets (if any). It doesn't need any conditions since it runs against the condition supplied to the if
block.if
block has a true
condition, the else
block is skipped entirely. Similarly if it's false
, then the if
block is skipped.if
block, the else
block can run without brackets {}
as well.else
block ends the series of if
s and else
s, such that another else
block can't come after one.The condition being supplied to the if
statements is not limited to values, but a large range of expressions. Here's how to tackle with various situations while working with if
statements:
To compare multiple values in if
statements, you can use the &&
(And operator) or ||
(Or operator) operators. They are used between two values, and decide according to their values.
The And operator, represneted by two &s like &&
, is used to match both of the values together (between which the operator is present). If any of the target values evaluates to false
, it returns false
. This operator behaves the same as the AND logic gate. For the operator to return true
, both of the values need to return true
.
Let's consider a little real life example. We want to eat some pizza 🤤 but we won't be ordering it until we check that we have some good apples at home first. So first we see that we have apples, and they are good too (we don't want to eat bad rotten apples), so we will eat apples instead. If any of the two conditions is incorrect, we order a pizza instead.
var weHaveApples = true;
var applesAreGood = true;
if (weHaveApples && applesAreGood) { // If we have apples, and apples are good too
eatSomeApples(); // Then eat some apples
// This code will only let us eat apples if they are available as well as are good in taste - we don't want to eat bad apples
} else {
orderAPizza(); // else order a pizza instead :D
// We will only be ordering a pizza if we don't have good apples
}
if (A && B) {
X();
}
is same as this:
if (A) {
if (B) {
X();
}
}
but shorter and simpler. (where A
and B
are two variables or values, and X
is a function.)
Functions are simply tasks that we can perform. Functions are wide spread through JavaScript. All the jobs we perform like console.log()
, alert()
and parseInt()
etc. are all functions.
We obviously know that anything like eatSomeApples()
or orderAPizza()
as mentioned above isn't a real function. This is just to represent a task that will be performed. Functions can be user defined as well, but that is an advanced topic. You might find examples online representing some example code (like telling a rough idea about what will happen in a certain line of code) as functions, since coding with well defined functions is a good idea, since it improves code readability.
The eatSomeApples()
function is just a dummy function used for explaination only, representing a real life task in this case.
The ||
operator acts as an "OR" between two values. This will return true
, of either of the target values is true.
Let's take an example here as well. We want to eat (again), and now we have two fruits to eat. We want to eat fruit, if any one of them is available.
var weHaveApples = true;
var weHaveBananas = false; // We don't have bananas at home :(
if (weHaveApples || weHaveBananas) { // If we have apples or bananas
eatFruit(); // We eat fruit 😋
} else { // Else we cry about it 😢
alert("Nothing to eat! :(");
}
By now, you have learned how to manipulate booleans with if
statements in various ways. That's mostly enough for booleans. But there are lots of other expressions that work like booleans too, like string comparisons, number comparisons, or obviously functions too (as you have used confirm
functions inside if
conditions). if
statements are very common, so they are really flexible as well. Here, we will look at comparing strings, and numbers.
If you want to match two values, like to check if two values are equal, you use the ==
(equals) operator. This works with strings as well as numbers.
The equals operator matching is case sensitive.
var questionInput = prompt("Do you like this document? (say 'Yes' or 'No')");
if (questionInput == "Yes") {
alert(":)");
} else {
if (questionInput == "No") {
alert(":(");
}
}
Since the equals operator matching is case sensitive, we can use the ||
(or) operator to match multiple values with varying cases:
var questionInput = prompt("Do you like this document? (say 'Yes' or 'No')");
if (questionInput == "Yes" || questionInput == "yes" || questionInput == "YES") {
alert(":)");
} else {
if (questionInput == "No" || questionInput == "no" || questionInput == "NO") {
alert(":(");
}
}
This is a bit lengthy, isn't there a way to convert strings into uppercase or lowercase? So that we can convert the user input to lowercase, and compare a lowercase "yes" or "no" with the input (so that the uppercase or lowercase doesn't matter anymore)? This topic belongs to the String & Number Methods below.
if (A) {
// ...
} else {
if (B) {
X();
}
}
is same as this:
if (A) {
// ...
} else if (B) {
X();
}
but shorter and simpler. (where A
and B
are two variables or values, and X
is a function.)
Comparing numbers is same as how you do it in Maths. All the >
(less than), <
(greater than), ==
(equals), <=
(less than or equal to) and >=
(greater than or equal to) operators work exactly like maths.
Here's a large example demonstrating all of these operators:
var age = parseInt(prompt("How old are you?")); // Converting to number since we need age in numeric form
// Some Normal Responses
if (age >= 18) {
// Age is equal to or above 18
alert("You're an adult!");
} else if (age < 18) {
// Age is less than 18
alert("You're a teenager.");
} else if (age < 13) {
// Age is less than 13
alert("Heh, kiddo.");
}
// Some funny ones
if (age == 69) {
// Age is 69
alert("Nice!");
} else if (age < 0) {
// Age is negative
alert("Stop messing with me and enter a real age 😡");
} else if (age > 150) {
// Age is above 150
alert("How are you even alive 🤔");
}
else if
blocks:As mentioned above, the else if
operator is just short for using a nested else
and if
combo.
Since an if
block or an else
block can be used without braces, a nested if
block can directly be written right after the else
keyword.
Look at this step by step example simplfying the nested form into the else if
form:
if (A) {
// ...
} else {
if (B) {
X();
}
}
if (A) {
// ...
} else {if (B) {
X(); // remove extra new lines, tabs and spaces
}}
if (A) {
// ...
} else if (B) {
X(); // remove extra brackets
}
You might be thinking, that if the brackets are to be removed, the body of the block must not exceed one line, but here, another if is being fitted into the else block, which can't exceed one line. That's because since the if
statement has it's own brackets, so any lines inside those brackets are included in the if
block, and are part of that. That one mandatory line is the if (B)
part, which ends here and starts brackets.
I know you didn't understand anything above. But try to practice various conditions using the else if
block. They're used a lot in programming so you should have lots of practice for them. Here are some tasks to do related to it:
Really simple, input their age, and respond with if they are an adult (age is 18 or more) or a teenager (age is 13 or more) or none (if none of the before conditions matched).
Simply input number and check if its even or not, google how to check even number in JavaScript. Your googling skills need to be tested too.
Make a variable password
, and put some string in it. Next, input a password from the user, and respond with whether the password was correct or not.
Make one round of a rock paper scissors game. Input the user's choice and store it in a variable (this is where you cheat ;) ). Then respond against the user's input, so that you can never lose. E.g. if the user inputs Rock, then respond with a scissors. Show the user's choice with your response (like "You chose: Rock. I chose: Paper. You lose.")
Please try to do them yourself before consulting these answers :(
var firstInput = prompt("Enter the first number:");
var secondInput = prompt("Enter the second number:");
var firstNum = parseInt(firstInput);
var secondNum = parseInt(secondInput);
var sum = firstNum + secondNum;
alert("The sum of the two numbers is:\n" + sum);
alert("The sum of the two numbers is:\n" + (parseInt(prompt("Enter the first number:")) + parseInt(prompt("Enter the second number:")))); // So many brackets! This is bad readability, should be prevented
// The reason I used brackets around the sum is so that the compiler solves the sum before it joins all values together. If no brackets are used, then the compiler begins to join values from left to right, resulting in both the numbers joined into a string (The left most part).
if (aZeroNumber) console.log("Condition Matched"); // This will not run.
if (anEmptyString) console.log("Condition Matched"); // This will also not run.
if (aBooleanValue) console.log("Condition Matched"); // This will run.
var age = parseInt(prompt("Enter your age"));
if (age >= 18) alert("You're an adult.");
else if (age >= 13) alert("You're a teenager.");
else alert("You're just a kid.");
var x = parseInt(prompt("Enter a number"));
if (x % 2 == 0) alert("The number is even");
else alert("The number is odd");
var password = "MyLittlePony";
var inputPassword = prompt("Enter Password");
if (password == inputPassword) {
alert("The password was correct");
else {
alert("The password was incorrect");
}
var response; // This is called creating a variable without initialization. Strict languages like C++ and Java require this, but here it's only for practice to create your variables at the beginning of your program.
var usersResponse;
var usersTurn = prompt("Welcome to Rock Paper Scissors!\n\nEnter your choice:\nR for Rock\nP for Paper\nS for Scissors");
if (usersTurn == "R") {
usersResponse = "Rock";
response = "Paper";
}
else if (usersTurn == "P") {
usersResponse = "Paper";
response = "Scissors";
}
else if (usersTurn == "S") {
usersResponse = "Scissors";
response = "Rock";
}
alert("You chose: " + usersResponse + "\nI chose: " + response + "\n\nYou Lose!");