JavaScript Practice

Aight um here are some well, JS programming tasks to do for practice, but with solutions so no need to worry :)

Fun thing to play with: This is made with CSS & JS:

Show
When
the
Impostor
Is
Sus

😳

Task 1: Create a simple Calculator:

Type: Pure JS (No HTML interface required)

Tags: promptif


In this task, you have to input 3 things from the user, to give the calculation result:

First, take first number as input, then take second number as input, and then take their operation as input.

The program should check that which operation is inputted, and perform the coresponding operation with the two inputted numbers.

The program should say "Invalid Operation" and exit, if the user inputs anything other than the 4 valid operands (+, -, *, /) while inputting the operation.

Images:

Show

Normal Behaviour:

Task 1 Image Task 1 Image

Invalid Operand:

Task 1 Image

Solution:

Show

First, lets break the whole task down to smaller tasks:

  1. Input both numbers (using prompt())
  2. Input the operation (using prompt())
  3. Check the operation using if statements (and say "Invalid Operation" if its invalid)
  4. Perform the inputted operation
  5. alert() the result

1. Input both numbers

This is obviously really simple, you have done it before. Store the prompt() value in a variable. Don't forget to convert it to number before storing, i.e. cover the prompt() expression with a parseInt() like this:

var firstNumber = parseInt(prompt("Enter first number"));
var secondNumber = parseInt(prompt("Enter second number"));

Now we have both numbers as we need them. In the number form.

2. Input the operation

This is also same as before; but the only difference is, we dont need to convert the operations into a numeric form.

var operation = prompt("Enter the operation between the two numbers: (=, -, * or /)");

Now we have all the data we need. Let's process it and give the user an output (the result).

3. Check the operation

Now, we need to check, that which expression did the user give us in the prompt box, and perform that operation. This one might seem tricky at first, but its just a bunch of if statements.

We are going to check, that if the operation variable is '+'. If so, add both numbers. If not, check that if the operation variable is '-'. If so, subtract both numbers. If not, then check the same for multiplication, and then eventually, for division.

This would happen like this:

if (operation == "+") {
    // add both numbers
} else if(operation == "-") {
    // subtract both numbers
} else if(operation == "*") {
    // multiply both numbers
} else if(operation == "/") {
    // divide both numbers
}

If none of the conditions ran, we will alert() the message, Invalid Operand. Simple, we use the else statement in the end, and put the alert in there.

    // divide both numbers
} else {
    alert("Invalid Operand.");        
}

This will cause a problem later. If you spotted it, then it means you are going great :)

4. Perform the inputted operation

Now, inside each if statement, we know what operatiom has the user inputted. Since each possibility has been tracked, we can perform our desired job inside each of the if statements.

if (operation == "+") {
    result = firstNumber + secondNumber;
} else if(operation == "-") {
    result = firstNumber - secondNumber;
} else if(operation == "*") {
    result = firstNumber * secondNumber;
} else if(operation == "/") {
    result = firstNumber / secondNumber;
} else {
    alert("Invalid Operand.");        
}

5. alert() the result

One final simple thing remaining, output what we have calculated using alert(), simple.

alert("The result is " + result + ".");

Done :) You can try running it now.

BUT WAIT

Our work is done, but there exists a bug in our code if you have noticed. When we give an invalid operand, and press enter, we get Invalid Operand as intended. But when we close that popup, we get an error!

Q. WTF dude??? JS IS STUPID, DUMB ERRORS THAT COME OUT OF NOWHERE, HTML WAS BETTER

A. The reason is that the result variable doesnt even create when the result is attempted to display, and when the result popup tries to get the value of result, it doesn't find it, and gives an error. Also, we want to prevent the result popup from displaying when this happens. So, we will use another check, that if the result variable has created, alert the result. If not, do nothing.


One way of fixing this is to first make the result variable before all the if statements, and set its value to false. (The false value is for a reason)

var result = false;
if (operation == "+") {
    result = firstNumber + secondNumber;  

Now, we will have some scenario like this: if the inputted operand was correct, the result variable will contain the result. If its not, then it will remain false. Now, when the operand is invalid, i.e. the result variable is false, then we don't have to alert() the result. OR, We only have to output the result, when the result is not false, that is;

if (result !== false ) alert("The result is " + result + ".");

What is !== | Why !== over !=

The !== and === are used for strict comparisons and != and == are used for regular comparisons.

The !== saves us from another bug. In JavaScript, the code 0 == false returns true, i.e. it's believed that 0 is equal to false. This is the clumsiness of JavaScript, and mostly doesnt exist in other languages. Similarly, 1 == '1' is also true. This means that without using strict comparison, if our result variable turned out to be zero, (like if the user did something like 3 - 3, which is zero), then our code will break, since it thinks that 0 is false. To overcome this, we use strict comparisons. While using strict comparisons, 0 === false returns false, which means, this is what we want.



The complete code:

var firstNumber = parseInt(prompt("Enter first number"));
var secondNumber = parseInt(prompt("Enter second number"));

var operation = prompt("Enter the operation between the two numbers: (=, -, * or /)");

var result = false;
if (operation == "+") {
    result = firstNumber + secondNumber;    
} else if(operation == "-") {
    result = firstNumber - secondNumber;    
} else if(operation == "*") {
    result = firstNumber * secondNumber;    
} else if(operation == "/") {
    result = firstNumber / secondNumber;        
} else {
    alert("Invalid Operand.");        
}

if (result !== false ) alert("The result is " + result + ".");

Task 2: Password Check:

Type: Pure JS (No HTML interface required)

Tags: comparisonprompt


This task is smaller than the previous one. In this, you have to make a password variable, (which will act as the storage of the user's password), and then input the password, check if the password is correct, and output Access Granted or Incorrect password according to the condition.

Images:

Show

Incorrect password:

Task 2 Image

Correct password:

Task 2 Image

Solution:

Show

First, store the password

Make a variable named password, and write its value to any password you want. For this example, I'll use SecretPassword123

var password = 'SecretPassword123';

Input the user's password

Now lets store the user input in a variable called inputtedPassword. This will be used to compare the actual password to the user's password.

var inputtedPassword = prompt("Enter password");

Check the password

Really easy. Just toss both values into an if statement. Compare both values (using strict or normal comparison, normal comparison won't be messing with us this time), if true, say that Access Granted, else, alert Incorrect Password

if (inputtedPassword == password) {
    alert("Access Granted");
} else {
    alert("Incorrect password");
}

Aaaand we are done. No surprises this time.



The complete code:

var password = 'SecretPassword123';

var inputtedPassword = prompt("Enter password");
if (inputtedPassword == password) {
    alert("Access Granted");
} else {
    alert("Incorrect password");
}

Task 3: Joining Values:

Type: Full HTML Page

Tags: HTMLinputDOM


Create an HTML file, name it, give it a title, add CSS, all according to your choice.

Now create 4 elements:

When the button is clicked, the text tag should change its text to the combined values of both input fields.

Using a function is recommended since it is a more cleaner method.

Images:

Show

Join button clicked:

Task 3 Image

Solution:

Show

First, create the HTML UI and give appropriate IDs:

Now, we will create a function named setJoinedText, which will perform the main job. Lets add an onclick event for it first:

Now, to write some JavaScript, we open the script tag in the bottom:

Now, lets count all the stuff we need to do when the button is clicked:

  1. Get the two input fields
  2. Extract and join their value
  3. Get the text tag
  4. Set the text of the text tag to the joined value of the both extracted input values.

1. Get the two input fields

First, lets create the function:

function setJoinedText() {

}

Now, lets get both the input fields, and store them into the variables input1, and input2

function setJoinedText() {
    var input1 = document.getElementById('input-1');
    var input2 = document.getElementById('input-2');

}

2. Extract and join their value

We will do this part while setting the text of the text tag.

3. Get the text tag

Now, like the input fields, we get the text tag, and store it into the variable textTag.

function setJoinedText() {
    var input1 = document.getElementById('input-1');
    var input2 = document.getElementById('input-2');
    
    var textTag = document.getElementById('text');
}

4. Set the text of the text tag

Now lets join the values of both inputs, and set the text of the text tag to that joined value.

The text of any input field is present in its value property, not the innerText (I used to confuse these long ago). To set the value, we change the innerText of the text tag to our desired value.

I will do this in one step, be aware of what I did:

function setJoinedText() {
    var input1 = document.getElementById('input-1');
    var input2 = document.getElementById('input-2');
    
    var textTag = document.getElementById('text');
    textTag.innerText = input1.value + input2.value;
}

And now, we are done :)



The complete code: