JavaScript/Control structures/Exercises

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Topic: Conditional Branches



1. Write a script that allows a user to type in his name (prompt). The script shall answer depending on the length of the name.

  • Up to 5 characters: "Hello, <name>. You have a short name."
  • Up to 10 characters: "Hello, <name>. You have a name with a medium length."
  • Greater than 10 characters: "Hello, <name>. Your name is very long."
Click to see solution
"use strict";

const name = prompt("Please type your name: ");
const len = name.length;

if (len <= 5) {
  alert("Hello " + name + ". Your have a short name.");
} else if (len <= 10) {
  alert("Hello " + name + ". You have a name with a medium length.");
} else {
  alert("Hello " + name + ". Your name is very long.");
}



2. Write a script that allows a user to type in a single character. The script shall decide whether it is a vocal ('a', 'e', 'i', 'o', 'u') or a consonant.

  • "You typed in the vocal: <user's input>"
  • "You typed in the consonant: <user's input>"
  • "You typed in a digit or some other character (+, -, *, ...): <user's input>"
Click to see solution
"use strict";

const char = prompt("Please type a character: ");
const char2 = char.substring(0, 1).toUpperCase();

switch (char2) {
  case 'A':
  case 'E':
  case 'I':
  case 'O':
  case 'U':
    alert("You typed in the vocal: " + char);
    break;

  case 'B':
  case 'C':
  case 'D':
  // ... all the other consonants
    alert("You typed in the consonant: " + char);
    break;

  default:
    alert("You typed in a digit or some other character: (+, -, *, ...): " + char);
    break;
}



3. try / catch

  • Write a script that calls a functionconnectToDatabase(). This function does not exist in your script, which causes the JavaScript engine to generate a runtime error.
  • Catch the error and produce a meaningful error.
  • Terminate the script.
Click to see solution
"use strict";

try {
  connectToDatabase();
  // ... SQL commands ...
} catch (err) {
  alert("The function 'connectToDatabase()' is not known. System error?");
  alert("The system error is: " + err);
} finally {
  // ... show 'good by' screen
  alert("Program terminates.");
}



1 What is the result?

"use strict";

const x = 0;
let y = 0;

if (x < 10) 
  alert("One");
  y = 20;

if (y === 0)
  alert("Two");

A single message
Two messages

2 What shows the 'alert' statement?

"use strict";
let x = 2;
switch (x) {
case 1:
  x++;
case 2:
  x++;
  x++;
case 3:
  x++;
  x++;
  x++;
default:
  x = 0;
} //
alert(x);

0
2
4
None of the above