Learn JavaScript in Construct, part 5: Functions

21

Index

Stats

8,403 visits, 22,304 views

Tools

Translations

This tutorial hasn't been translated.

License

This tutorial is licensed under CC BY-NC 4.0. Please refer to the license text if you wish to reuse, share or remix the content contained within this tutorial.

Published on 15 Oct, 2021. Last updated 16 Dec, 2021

Some examples

Congratulations! You've now learnt enough JavaScript that we can write some useful mini-programs. To keep the examples simple, let's write some code that can list certain numbers.

List even numbers

Here's some code that will log all even numbers up to 50 to the console.

function isEven(n)
{
	return n % 2 === 0;
}

for (let i = 1; i < 50; i++)
{
	if (isEven(i))
	{
		console.log(`Number ${i} is even`);
	}
}

The function isEven returns a boolean (true or false) indicating if the parameter n is an even number. It makes this check using the remainder operator %: if the number divided by 2 has a remainder of zero, then it is a multiple of two, and hence an even number.

Then this function is called for every number from 1 to 50 using a 'for' loop. Note it is called inside an 'if' statement, so if the function returns true, the code inside the 'if' statement will run, and that code logs the number to the console stating it is an even number.

List prime numbers

A prime number is a number that has only itself and 1 as factors, or in other words, there are no two whole numbers that multiply to make that number other than itself and 1.

A simple way to check if a number n is a prime number is to check if it is the multiple of any number from 2 to the square root of n. This can also be done with a 'for' loop. Here's some code that will log every prime number from 1 to 100.

function isPrime(n)
{
	// 1 is not a prime number
	if (n === 1)
		return false;
	
	// Raise to power of 1/2 takes square root
	let sqrtN = n ** 0.5;
	
	// Check for factors from 2 to square root of n
	for (let f = 2; f <= sqrtN; f++)
	{
		if (n % f === 0)
		{
			// Found a factor: not a prime
			return false;
		}
	}
	
	// Did not find any factors: is a prime
	return true;
}

for (let i = 1; i < 100; i++)
{
	if (isPrime(i))
	{
		console.log(`Number ${i} is prime`);
	}
}

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!

Next Tutorial In Course

Learn JavaScript in Construct, part 6: More on functions 15:10

Covers more details about functions in JavaScript, including function expressions, recursion, arrow functions and closures.

  • 2 Comments

  • Order by
Want to leave a comment? Login or Register an account!