JavaScript assignment question

My husband is a software developer. He is helping me learn web development. He wrote me the following assignment:

Write and test a JavaScript program that:

  1. Asks the user “Enter two integers separated by a space”.

  2. Test the input.

-If the input is two integers separated by a space, add the integers together and output the result to the screen.

-If not, output “Invalid Input” to the screen.

So far, this is what my code looks like:

var a = 1;
var b = 2;
function numbers(a, b) {
  if (//i don't know what to write here)  {
     return (a + b);
  else {
      return "Invalid Input";
numbers(a, b);

Clearly I need more practice. Does anyone have pointers how to move forward with this problem?

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.


Where do you have the place for the input with the two integers separates by a space?

Once you have that you can put in that condition to check if the input is actually like that or not, so if it is not it will go to the else statement

I always start by breaking down my function objectives. Your function must:

  1. Ask the user for input
  2. Ensure input has the correct format
  3. Separate integers from the string input
  4. Add the integers together and return

Starting with point 1, how would you ask the user for input in Javascript? The prompt() function might do something like this for you.

Point 2. The input must be:

  • a string object
  • take the form “(integer)(space)(integer)”

Well if you use the prompt() function to get the input, point one is resolved as it only returns strings or a null object (someone canceled the prompt). Once you know the input is a string, it needs to be checked that it takes the right form. Well the job of parsing strings normally falls to Regular Expressions. In this case the expression /\^d+ \d+$/ could be used to ensure the input takes that exact form.

Step 3 is splitting the input string into an a and b. Well fortunately, string objects have a nifty String.split(sep) function that accepts a string type separator, it will return an array containing the string parts broken apart at the seperator character (a single space in this case). These could be assigned to a and b but the ‘string type integers’ needs to be converted to Number objects before they can be added together.
Note about JS: the + operator will add two Number objects together, but it defaults to concatenation for String objects. ('1' + '1' --> '11', 1 + 1 --> 2)

Finally add and return.