JavaScript Document 2 — More Programming

The second document continues the first one, further discussing concepts in JavaScript programming
This is a work in progress.

Table of contents:


Taking Input from user:

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.

A bit detail about it:

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:

What would happen if we try to perform arithmatic on the numbers from prompt without converting it into a number form first?

Performing Arithmatic with Input:

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.

The 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.

Why can't we change the buttons text?

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.

Type Conversion:

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));
					

Using commas in console.log():

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.

Task to do : A simple calculator

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.

Task to do : A simple calculator without variables

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 :)

If statements:

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:


						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.
						}

					

Task to do : If statements without brackets

Try typing the above three if conditions without using the {} brackets, as mentioned above as "compact form".

String & Number Methods:

 

Task to do answers:

    Please try to do them yourself before consulting these answers :(

  1. 
    						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);
    					
  2. 
    						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).
    					
  3. 
    						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.
    					
  4. 
    						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.");
    					
  5. 
    						var x = parseInt(prompt("Enter a number"));
    						
    						if (x % 2 == 0) alert("The number is even");
    						else alert("The number is odd");
    					
  6. 
    						var password = "MyLittlePony";
    
    						var inputPassword = prompt("Enter Password");
    						if (password == inputPassword) {
    							alert("The password was correct");
    						else {
    							alert("The password was incorrect");
    						}
    					
  7. 
    						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!");
    					

Next: JavaScript Document 3