JavaScript Functions
JavaScript Functions
Learning Objectives
This lesson provides an overview of functions within JavaScript. By the end of this lesson, learners will be able to:
Identify the structure of a function.
Create and call a function.
Use function syntax with parameters and arguments.
Create a variable with scope and hoist.
Use the debugger to locate and view different types of JavaScript errors.
Table of Contents
Functions in JavaScript
Defining a Function
Function Syntax in JavaScript
Calling a Function
Returning a Function
Variable Scope in JavaScript
Hoisting in JavaScript
Debugger
Errors
try...catch
Strict Mode
Functions in JavaScript
A function is a block of JavaScript code that is defined once but may be executed or invoked any number of times. Creating functions for repeated tasks can help to keep your code concise, organized, and efficient.
JavaScript functions are parameterized: a function definition may include a list of identifiers known as parameters that work as local variables for the body of the function.
Function invocations provide values or arguments for the function's parameters. Functions often use their argument values to compute a return value that becomes the value of the function-invocation expression. In addition to the arguments, each invocation has another value in the invocation context - the value of the this keyword.
If a function is assigned to the property of an object, it is known as a method of that object. When a function is invoked on or through an object, that object is the invocation context or this value for the function. Special functions designed to initialize a newly created object are called constructors.
In JavaScript, functions are objects, and they can be manipulated by programs. JavaScript can assign functions to variables and pass them to other functions. For example, since functions are objects, you can set properties on them and even invoke methods on them.
Defining a Function
Functions are defined with the function keyword, which can be used in a function definition expression or in a function declaration statement. In either form, function definitions begin with the keyword function followed by these components:
An identifier that names the function. The name is a required part of function declaration statements; it is used as the name of a variable, and the newly defined function object is assigned to the variable. For function definition expressions, the name is optional. If present, the name refers to the function object only within the body of the function itself.
A pair of parentheses around a comma-separated list of zero or more identifiers. These identifiers are the parameter names for the function, and they behave like local variables within the body of the function.
A pair of curly braces with zero or more JavaScript statements inside. These statements are the body of the function. They are executed whenever the function is invoked.
Function Syntax in JavaScript
A breakdown of the syntax of a function is as follows:
function - keyword that allows JavaScript to know that this is a function.
nameoffunction - Identifier that can be referenced in order to use this function.
parentheses - Data in the form of variables (parameters) that can be passed to the function. If the function does not take any parameters, the parentheses are left empty.
curly brackets - Body of the function, and a set of instructions that will be executed whenever the function is called.
function name0ffunction(parameter1, parameter2, parameter 3 ) {
// body of the function
}
Calling a Function
When a function is declared, the variables inside the parentheses are called parameters; however, when calling a function, the variables inside the parentheses are called arguments. This is because in the declaration of a function, the parameters can only be variables.
Declaring and defining a function does no good if the function is not used. To use a function, you must call the function. When calling a function, the arguments can be variables and/or literal values. To perform a function call, do the following:
Specify the identifier (function name).
Follow-up with parentheses and the number of arguments.
End with a semicolon.
Examples of calling a function with and without parameters will be given on the next slide.
Calling a Function - Examples
Functions without Parameters
This function takes no parameters; therefore, the parentheses are left empty. Notice the indentation of the function and within its body.
Example:
// Define the function.
function defaultmessage() {
console. $\log ($ "Default message") ; 子
// Call the function. defaultMessage( );
Function with Parameters
This function takes two parameters; however, there is no information as to what the data types are of these parameters. Therefore, having scripts well-documented will go a long way.
Example:
function customMessage(custom, times) {
for (let $i=0$; $i$ <imes; $i++$ ) {
console. $\log (i$, custom) ;
}
}
customMessage("Hello!", 3);
Returning a Function
In other languages, such as Java, when a function is defined, the return type of the function must also be defined. However, with JavaScript, a function can return a value, and it does have to be defined differently from functions that do not return a value.
Since functions are just a set of instructions that can perform a series of tasks, it is useful to have the function return a value as the result of the set of instructions. For example:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_4e33baf59ec8f252d9e7g-09.jpg%3Fheight%3D372%26width%3D631%26top_left_y%3D714%26top_left_x%3D271&width=768&dpr=4&quality=100&sign=f58142f8&sv=1)
Variable Scope in JavaScript
The scope of a variable is the region of your program source code in which it is defined. A global variable has global scope; it is defined everywhere in your JavaScript code.
Within the body of a function, a local variable takes precedence over a global variable with the same name. For example:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_4e33baf59ec8f252d9e7g-10.jpg%3Fheight%3D494%26width%3D1279%26top_left_y%3D665%26top_left_x%3D271&width=768&dpr=4&quality=100&sign=e8e5df9&sv=1)
Variable Scope in JavaScript (continued)
Function definitions can be nested. Each function has its own local scope, so it is possible to have several nested layers of local scope. For example:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_4e33baf59ec8f252d9e7g-11.jpg%3Fheight%3D728%26width%3D1628%26top_left_y%3D517%26top_left_x%3D268&width=768&dpr=4&quality=100&sign=fd65adc6&sv=1)
Hoisting in JavaScript
Hoisting refers to the idea of JavaScript bringing all (any) object declarations to the top of their scope prior to execution of the code. This allows you to use functions and variables before they are declared. It is important to understand that this only works for declaration, not initialization of an object.
To understand hoisting let's reference the example to the right:
The declaration of the hoist () function comes after we call it, but because the declaration is hoisted, there is no error with the way the code is written. However, since the const $\mathbf{x}$ declaration "taints" its scope, attempting to print the value of $x$ within hoist () will cause a ReferenceError, because $\mathbf{x}$ is not yet initialized within that scope.
Debugger
The debugger keyword gives the developer control over the execution of the program. The debugger keyword stops execution at the line where it is encountered. In other developer languages, this is called a breakpoint.
Using the example to the right as reference:
If you open the script in a browser, you will notice that it appears to be loading. This is because the program has stopped and is waiting for instructions.
The powerful feature of debugger is that it allows the developer to see the values of all of the variables declared. This is helpful in case your program is crashing because of some value format.
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_4e33baf59ec8f252d9e7g-13.jpg%3Fheight%3D744%26width%3D1248%26top_left_y%3D543%26top_left_x%3D1168&width=768&dpr=4&quality=100&sign=ea4d6cb3&sv=1)
Debugger (continued)
Errors
There are many different types of errors that you will encounter when using JavaScript. We will go over the most common errors here:
A runtime error is a program error that occurs while the program is running. The term is often used in contrast to other types of program errors, such as syntax errors and compile time errors. There are many different types of runtime errors.
Logic errors produce the wrong output. For example, a miscalculation in the source code or a spreadsheet program may produce the wrong result when a user enters a formula into a cell.
Memory leaks cause a program to continually use more RAM while the program is running. A memory leak may be due to an infinite loop not de-allocating unused memory, or for other reasons.
JavaScript allows the developer to create a custom error when a runtime error occurs.
const err = new Error('Custom Error made by the developer.'); console. $\log (\mathrm{err})$;
Errors: try...catch
A try... catch statement is used to account for errors that may occur, and consists of two blocks.
The try block is meant to run code that can possibly crash the program. This code would be placed inside a try block in case there is a runtime error. The program will not just stop when it encounters the error; it will try to handle the error via the catch block.
When an error is thrown, the program will jump to the catch block. Therefore, a try block must never exist without a catch block.
The function someFunction is assumed to have code that can crash the program. Note that in this case, we are explicitly throwing an error. Normally, runtime errors would be thrown automatically by the program when they are encountered.
When the throw keyword is encountered, the custom error is raised, and the program jumps to the catch block.
Strict Mode
JavaScript has an opt-in mode called strict mode (the default version is often referred to as sloppy mode). Strict mode makes a number of changes to regular JavaScript semantics, including the following (taken from the reference linked below):
Eliminates some JavaScript silent errors by changing them to throw errors.
Fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that is not strict mode.
Prohibits some syntax likely to be defined in future versions of ECMAScript.
Before going forward, take 30 minutes to read this documentation about JavaScript strict mode, as it will be useful for you going forward:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict mode
Knowledge Check
What is a function, and how is it different from a method?
What are parameters, and how are they different from arguments?
What does the return statement do?
What is the difference between global and local scope in JavaScript?
What is hoisting?
What can the debugger keyword accomplish?
What are some common errors that you could encounter in JavaScript?
What is the statement used to handle errors?
What is strict mode, and why is it useful?
Summary
Functions are used to create blocks of code that can be called repeatedly without the need to include them multiple times within source code.
Functions can take parameters to use as local variables during their execution.
When a function is called, it can return a value based on the code executed within it.
Variables can be declared inside or outside of code blocks and functions, and have a scope that limits their use when declared inside of blocks.
Hoisting refers to the JavaScript interpreter bringing all variable declarations to the top of their scope, which allows you to use certain elements before they are declared. Hoisting can be useful, but also dangerous if misused or not accounted for. Best practice dictates that all variables should be declared at the beginning of their scope to avoid issue.
The debugger keyword can allow you to pause your program mid-execution and analyze the state of variables and other elements.
JavaScript has many different kinds of errors, most of which can be handled by try...catch statements.
Strict mode changes regular JavaScript semantics to create a more "refined" version of the language, which adds future-proofing and a number of other features.
Questions?
Last updated