Functions are one of the basic building blocks of programming. As you will learn, functions do something in code. Whether that is compute some value that is returned to the main program, or do something else as a side-effect to the main program.
The Mozilla Developer Network (MDN) defines functions as follows;
Generally speaking, a function is a “subprogram” that can be called by code external to the function. Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function, and the function may return a value.
You have already been using functions. These include;
console.log("something to print");
prompt("something to say in a popup box");
window.write("print something to the DOM");
There are many “builtin” functions to JavaScript, which you will learn about and use as you progress.
JavaScript also allows you to define and use your own custom functions. This is a critical technique for writing easily maintainable code that is well structured. As such, you will spend a lot of time this week learning about writing your own functions and how they can be used.
As you will learn about in more detail below, functions are called through the invocation of their name, followed by the function operator (()
).
someFunction();
Within in the function operator, you can supply parameters to the function.
someFunction( param1, param2 );
Function parameters are pieces of data that the function uses towards computations or as information to do something with.
There are generally three ways to define your own functions in JS.
The first is to call the function
keyword, followed by;
{}
) to execute when the function is invoked.The second way of defining functions is through function expressions, these assign a function to a binding namespace (i.e. a variable).
Function Expressions work the same as Function Definitions, the primary difference is that Function Expressions must be defined before they are called. Function Definitions are hoisted to the top of the JS interpreter and can be placed anywhere in the code, even after their initial call, as they will be compiled first.
The last type of definition you will learn about is Arrow Functions. This technique allows for the concise definition of functions, typically in a single line. This is useful when trying to write concise and clear code.
To get started, please read the following, which cover the usage and definition of functions in great detail;
Videos on the basic of Functions!
While you work on this chapter, you should use the following interactive JS console to test.