This combines a number of the things we've learnt so far. Here's a few notes on how the isPrime function works:
- 1 is not a prime number, but the function would otherwise return true for it, so we have to make an exception for it. So the function starts by checking if the number is 1, and exits early returning false if it is.
- Raising to the power of a half calculates the square root of a number. This could also use
Math.sqrt(n)
instead of n ** 0.5
(but this guide hasn't covered any of JavaScript's built-in math functions yet).
- The 'for' loop then checks every number from 2 up to and including the square root of the number. Note the loop starts the variable
f
at 2, and increments it so long as it is less than or equal to sqrtN
, which ensures it also checks if sqrtN
is a factor when it's a whole number.
- Similar to the check in isEven, we can check if
f
is a factor of n
using the remainder operator and checking if the remainder is zero. In that case n
is a multiple of f
, and therefore n
is not prime, so the function returns false.
- If the entire 'for' loop runs without returning, it means it did not find any factors of
n
. Therefore n
is prime, so the function returns true.
- Then similar to the previous example, a 'for' loop is used to check every number from 1 to 100 to see if it's a prime number, and log a message to the console if it is.
If you want to practice what you've learnt so far some more, try writing some more functions to test for different types of numbers, such as square numbers, and list all numbers from 1-100 that meet the test. Tip: you can test if a number is a whole number by using n % 1 === 0
, since in JavaScript the remainder operator works with fractions, so if the remainder divided by 1 is 0 then the number has no fractional part and so is a whole number. Then you can test for things like if the square root of a number is a whole number, which tells you if the number is a square number.
Conclusion
In this part we've covered:
- Using script files in Construct
- Declaring functions
- Calling functions
- Using function parameters
- The scope of variables, parameters and functions
- Returning values from functions
- Why to avoid a line break after
return
- Some examples combining everything covered so far to list numbers with certain mathematical properties
There's a lot more to functions in JavaScript, and so the next part of this guide will cover some more aspects of functions.
Learn more
If you want to dig deeper, you can learn more about the features mentioned in this guide at the following MDN Web Docs links:
Part 6
When you're ready to continue, head on to the next part at Learn JavaScript in Construct, part 6: More on functions!