Course: JavaScript

Progress (0%)

  1. Foundation

  2. Numbers

  3. Strings

  4. Conditions

  5. Loops

  6. Arrays

  7. Functions

  8. Objects

  9. Exceptions

  10. HTML DOM

  11. CSSOM

  12. Events

  13. Drag and Drop

  14. opt Touch Events

  15. Misc

  16. Project: Analog Clock

Exercise: Status Codes

Exercise 23 Easy

Prerequisites for the exercise

  1. JavaScript switch
  2. JavaScript if...else
  3. All previous chapters

Objective

Given an HTTP status code, print its corresponding status description.

Description

The World Wide Web (WWW), as you may already know, is backed by the HTTP protocol. It relies on a very intuitive and simplistic model of a client and server.

A client, such as a web browser, sends a request for a resource to a server that holds the resource. This request is formally called an HTTP request. Similarly, once the server receives the request and understands what exactly is asked in it, it then responds with an HTTP response.

Each HTTP response has a corresponding status which is comprised of a code and a description.

The status of an HTTP response is meant to specify what happened with the request, for e.g. whether it was responded to successfully, or whether there was an error in the request, or maybe an error in the server's code, and so on and so forth.

A status code, by that means, is the formal way to tell what happened with the request. It's a 3-digit number where the first digit represents the general class that the code belongs to.

For instance, all 2XX codes such as 200, 201, 202 imply 'success'. Similarly, all 4XX codes, such as 401, 402, the well-known 404, represent 'client error'. The list of possible codes is defined by RFC 9110.

Each status code has a corresponding description to make it easy for people to understand the meaning of the status code in HTTP responses, right away. For example, 404 has the description Not Found, which implies that the requested resource doesn't exist on the server.

All the five HTTP status code classes also have corresponding descriptions so that we can get a general idea, just by looking at a status code, of what happened with the sent request.

As defined by RFC 9110, here's the list of all the five classes:

  • 1XX: Informational
  • 2XX: Successful
  • 3XX: Redirection
  • 4XX: Client Error
  • 5XX: Server Error

In this exercise, you have to create a program that asks the user to enter a status code and then outputs a string representing the class that the code belongs to.

The status code must be obtained via an input prompt and then the corresponding output be made via an alert message.

Keep in mind that it's possible for the user to enter some arbitrary text into the prompt, likewise you MUST validate the input as follows:

  1. If the length of the text is not 3, alert 'Invalid code length.'
  2. Otherwise, if either of the three characters is not a digit, alert 'Each character must be a digit.'
  3. Otherwise, if the first digit is not in the range 1-5, alert 'First digit not in range 1-5.'

Simple.

As an example, suppose we enter the text '301' into the input prompt. The output should then be 'Redirection'. Similarly, if we enter '600', the output should be 'First digit not in range 1-5.'

Note that your solution MUST use the switch statement.

And you are obviously free to create as many helper functions as you want to, as long as they improve the overall readability and simplicity of the code.

Remember that we haven't structured this exercise to literally pinpoint out-of-range status codes for each code class. For instance, the code 250 isn't defined in RFC 9110, yet it'll work absolutely fine in this program. So, if you want to, you could maybe take the exercise a step further and even check whether the input status code is in-range for its respective class.
View Solution

New file

Inside the directory you created for this course on JavaScript, create a new folder called Exercise-23-Status-Codes and put the .html solution files for this exercise within it.

Solution

The very first thing that we'll do is create a function that takes in a status code, as a string, and then returns back the description of the class it belongs to. We'll call this function getStatusCodeClass().

And since we ought to compare the first digit of the status code with different digits, precisely 5 of them, in order to determine its class, and as instructed in the exercise's description above, we'll use a switch in this regard.

Here's the definition of getStatusCodeClass():

function getStatusCodeClass(statusCode) {
   switch (statusCode[0]) {
      case '1':
         return 'Informational';
      case '2':
         return 'Successful';
      case '3':
         return 'Redirect';
      case '4':
         return 'Client Error';
      case '5':
         return 'Server Error';
   }
}

Next up, we'll create another helper function to determine if a given character represents a digit. We'll call it isDigit(), clearly indiciating that the function returns back a Boolean (by virtue of the word 'is'):

Following is the definition of isDigit():

function isDigit(char) {
   return '0' <= char && char <= '9';
}

Remember that we're assuming that char is a string, not a number and that's why we compare it with stringified digits, i.e. '0' and '9'.

With this done, we'll define another function, this time to check if the first digit of the status code is in-range. We'll call the function isFirstDigitInRange():

function isFirstDigitInRange(statusCode) {
   return '1' < statusCode[0] && statusCode[0] < '5';
}

With all these three helper functions defined, we can now just go on and lay out a bunch of if and else statements to check whether the given input is valid, and if it is, then output the status code's corresponding class.

Here's the complete code:

function getStatusCodeClass(statusCode) {
   switch (statusCode[0]) {
      case '1':
         return 'Informational';
      case '2':
         return 'Successful';
      case '3':
         return 'Redirect';
      case '4':
         return 'Client Error';
      case '5':
         return 'Server Error';
   }
}

function isDigit(char) {
   return '0' <= char && char <= '9';
}

function isFirstDigitInRange(statusCode) {
   return '1' <= statusCode[0] && statusCode[0] <= '5';
}


var statusCode = prompt('Enter status code:');

if (statusCode.length !== 3) {
   alert('Invalid code length.');
}
else if (!isDigit(statusCode[0]) || !isDigit(statusCode[1]) || !isDigit(statusCode[2])) {
   alert('Each character must be a digit.');
}
else if (!isFirstDigitInRange(statusCode)) {
   alert('First digit not in range 1-5.');
}
else {
   // The input was valid, hence we must make the desired output.
   alert(getStatusCodeClass(statusCode));
}

Live Example

Voila!

This isn't the only solution!

Remember that the solution shown here is not the only way to approach the problem described above.

If we want to, we could come up with different kinds of helper functions instead of the ones shown here. Or we could even get done without any helper functions at all, but might make the code a little less readable, especially when we'll have to lay out complex conditions.

For example, instead of using isDigit() manually on each of the three characters of statusCode, we could create a single isAllDigits() function to encapsulate this entire logic, and have to do something as follows:

/* ... */

if (statusCode.length !== 3) {
   alert('Invalid code length.');
}
else if (!isAllDigits(statusCode)) { alert('Each character must be a digit.'); } else if (!isFirstDigitInRange(statusCode)) { alert('First digit not in range 1-5.'); } else { // The input was valid, hence we must make the desired output. alert(getStatusCodeClass(statusCode)); }

There are just tons and tons of ways to approach the same problem.

Whatever solution you're able to come up with should meet the following two prerequisites in order to be classified as a perfect one:

  • Obviously produce the correct output.
  • Be simple and readable.