JavaScript Logical Error

To Whom It May Concern,

My name is Prakash and I believe I have a logical error in my code. I am fairly new to JavaScript and I would appreciate it if someone could help me. My source code is below. Thank you.

https://jsfiddle.net/pherami1/jfh3xq69/2/

Hi there @pH1, lovley to meet you, and welcome to the community!

I had a look at your code, and I can see what you are trying to do. It is very close to working, but there are just a few small items that need fixing up.

First, in your if statement, you are trying to run a test on the <input> element itself, not its value. To reference the value, you need to use input.value. In addition to that, you need to compare the current statement to see whether it is equal to 0 — even numbers leave no remainder when divided by 2.

So I changed it to this:

if (input.value % 2 === 0) {

Next, you didn’t put your string values in quote marks, so you were getting undefined returned when you later referenced result — the browser thoght you were referencing variables that didn’t exist, rather than strings. So I updated them to this:

result = 'even';
} else {
result = 'odd';

Finally, you again needed to update input to input.value in your final line in which you print the results:

document.getElementById('para').textContent = input.value + " is an " + result + " number.";

I think that’s it. The full script now looks like this:

const input = document.getElementById('textInput');
const button = document.getElementById('submitButton');

button.addEventListener('click', evenOrOdd);

function evenOrOdd () {
let result;
let even;
let odd;
if (input.value % 2 === 0) {
result = 'even';
} else {
result = 'odd';
}
document.getElementById('para').textContent = input.value + " is an " + result + " number.";
}

But as I said, you were pretty close. Don’t give up — you are doing great.

1 Like

Thank you Chris, I appreciate it.

You are very welcome.