How to make some basic JavaScript functions user interactive

Hi everybody!

This is my first post here, so let me briefly introduce myself.
My name is Bruno, I’m from Verona, Italy, and I’ve recently (well, it was June 2017) started studying and loving programming. After completing some basic courses about Web Dev on different platforms, I’ve decided to put all I’ve learned into practice. At the moment I’m studying JavaScript and facing a few problem sets (functions, arrays). Straight to the point now: I’d like to make some functions more user interactive, i mean, I want to grant the user the chance to input a value and return something.
For example, this function returns “true” if a number is even, and “false” if a number is odd:

function isEven(num) {
if (num % 2 === 0) {
return true;
} else {
return false;
}
}
isEven(4);

I changed it a little bit in order to make it user interactive:

var check = prompt(Number.num);
function isEven(num) {
if (num % 2 === 0) {
return true;
} else {
return false;
}
}
isEven(check);

Now, if I want to add the same feature for a more complex function which, say, return the factorial of a number, how can I proceed? I tried different approaches but I can’t wrap my head around it. This is the basic function:

function factorial(num) {
var result = 1;
for (var i = 2; i <= num; i++) {
result *= i;
}
return result;
}
factorial(4);

Thank you for the help

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a 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.

1 Like

The same way you did with the check variable which used the isEven function. Just assign the value returned from the prompt to a variable and call your factorial function with this variable.

var numToCalcFactorial = prompt('Enter a number for which to calculate the factorial');
factorial(numToCalcFactorital);
2 Likes

Just a little thing,

function isEven(num) {
if (num % 2 === 0) {
return true;
} else {
return false;
}
}

Can be simplified greatly by just returning the condition:

function isEven(num) {
return num % 2 === 0
}

or even simpler:

Hope this helps.

1 Like

Hi @kevinSmith,

Thank you for editing my post. I was in a rush and I forgot about good posting practices, my bad

I tried to declare the variable outside and inside the function the same way I did for the isEven(), but when I try it in the console it returns me a syntax error. Tomorrow I’ll give it another shot. Anyway, thank you for your reply!