Learn JavaScript in Construct, part 6: More on functions

18

Index

Stats

5,843 visits, 12,748 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.

This is part 6 of the tutorial series Learn JavaScript in Construct. This part continues on from part 5. So in case you missed it, see Learn JavaScript in Construct, part 5: Functions.

In this part we'll continue using a script file in a new Construct project. You can carry on with the same project as before, or create a new project and add a new script file again; either way delete all the code in the script file so you're starting with an empty file. In this part we'll cover more about functions. Since functions are such an essential part of programming, it's worth going in to some more detail about how they work and what you can do with them.

Function expressions

A function can also be used as an expression. In other words this means you can put function declarations in the same place as a number or string, such as assigning them to a variable, as shown below.

// Assign a function to a variable
let myFunc = function logMessage()
{
	console.log("Hello world!");
};

// Call the function held in the variable
myFunc();

When using a function this way, note it does not declare a function named logMessage, so calling logMessage() won't work. The only way to call the function is from the variable it was assigned to, i.e. myFunc(). In other words the function name isn't actually used here. In fact in this case the function name is optional, and so can be omitted like so.

// Function has name omitted
let myFunc = function()
{
	console.log("Hello world!");
};

myFunc();

Functions have a type of "function" when using typeof.

let myFunc = function()
{
	console.log("Hello world!");
};

console.log(typeof myFunc);	// function

Remember JavaScript is dynamically typed, meaning variables can have numbers, strings, or functions, assigned at any time - or have nothing assigned (undefined). If you try to call a variable as if it has a function in it, but it doesn't, it will cause an error when trying to call the function.

let myFunc = 5;		// not a function
myFunc();			// try to call it anyway
// TypeError: myFunc is not a function

Why use functions in variables? It allows for flexibility in what you do with functions, such as having a variable that is re-assigned different functions depending on what you want to do. This also demonstrates the principle of a function expression, which comes useful in other cases, as we're about to see.

Callbacks

Just like how functions can be assigned to variables, functions can also be passed as parameters to other functions.

This can be confusing at first, but is an important part of programming. In particular it allows for a pattern named callbacks, where a function can do some work, and then call another function with the result of the work.

To introduce the idea, here's an example of a function calling another function.

// Declare a function that calls the function passed as its parameter
function logReturnValueOf(func)
{
	console.log(`The function provided returned: ${func()}`);
}

// Call the above function, and also give it a function to call
logReturnValueOf(function ()
{
	return "Hello world!";
});

This will log to the console the message: The function provided returned: Hello world!

Notice how we have a function call to logReturnValueOf(...), and the parameter in between the ( and ) is a function expression for a function that just returns the string "Hello world!". Then inside the logReturnValueOf function, it calls its parameter with func(), and adds the returned value to a log message.

The syntax with these uses of functions may take some time to get used to. In particular you can end up with lots of pairs of ( ), { and } across different lines. However you should notice Construct's code editor, like most other coding editors, can highlight bracket pairs to help you match them up.

Returning functions

Functions can also return other functions.

You may be beginning to notice that in general, anywhere you can use a string or a number, you can also use a function. This is a useful feature of JavaScript, and is sometimes referred to as first-class functions, as functions can be treated the same as any other data type.

Here's an example of a function returning a function.

// Declare a function that returns another function
function getFunction()
{
	return function()
	{
		console.log("Hello world!");
	};
}

// Call getFunction(), which returns a function
let returnedValue = getFunction();

// Call the returned function, logging "Hello world!"
returnedValue();

Next Tutorial In Course

Learn JavaScript in Construct, part 7: Objects 20:49

Introduces objects, another key fundamental of JavaScript programming.

  • 0 Comments

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