JavaScript functions

Hello, I am very new to coding and I am learning with the books here, reading the forums and using online resources such as code academy. I am currently doing a function in JavaScript to see if a number is divisible by 2. here is the code:

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

isEven(10);

can someone explain the reason as to why the end is isEven(10) I do not understand what that does.

That’s the line of code that is calling the function (making it run). The parentheses contain the value that the function is going to work with. In this case, as 10 is divisible by 2 with no remainder, the function will return true.

If you open up your browser console, and paste that code in, you can test it out by calling the function with different values. Just remember that you won’t need to paste the function itself in again, UNLESS, you refresh the page.

Thank you very much I appreciate it. So to confirm you are saying I am calling the function and using the function dividing it by 10. If i made the number inside the parentheses an odd number it should come out as false.

Almost. The 10 is having a modulus operation done on it - in this case 10 modulus 2 which gives the result 0 i.e. no remainder.

Using modulus 2 is a common way of checking whether a number is odd or even, but you could use 3, 4, 5, or any other number, depending on what you’re looking for. Try looking up fizzbuzz and see how the same idea is used there.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.