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 :slight_smile:

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.

markdown_Forums

1 Like

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 :sweat_smile:

Hi @camperextraordinaire,

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!

Hi @IsaacAbrahamson,

Thanks for replying. I didn’t think about this short-hand approach. Looks interesting, but does it work also for longer, more complex functions?

You can always return a condition instead of doing an if/else there. If you have other logic inside your if/else however, it wouldn’t work as you can only return one thing. You usually can use other things though to make the functions more concise.

1 Like

Got it. Thank you so much for the clear explanation!