📖 JavaScript Functions
A function is a group of statements treated as a single unit. Functions are small portions of reusable code developed to ease overall coding by making these common tasks modular and accessible from other parts of your code. Functions work for programmers because it allows for the creation of small portable code to be used in multiple locations.
Rules for Functions
- Reserved word function is required
- function_name identifies the function. Rules same as for variables
- () required, even if no parameters.
- Parameters are optional. If used, they are arguments or data values that are passed to the function from the calling procedure. Multiple parameters are separated by commas. (param1, param2, param3)
- The JavaScript statements that compose the function are enclosed in curly brackets {}
- Functions are usually placed in the head section of a page or in an external JavaScript file.
- Parameters may be variables or values.
- Functions may or may not return a value.
Using Functions in JavaScript
Functions are designed to provide reusable blocks of code to improve the app structure. These code blocks must be defined with their functionality in mind. Like all code, they will only perform the task they were designed to perform. Once defined, they can be called within the code base to execute their functionality. Some functions are designed to modify values that are passed to the function during the function call. For example, if you want a function to calculate the tax on a purchase, you may need to pass the sale amount and provide the tax rate. These things could vary each time the function is called, so it could be expected that the values be provided at call time. Lastly, functions are often used to return a value.
To create a function definition
function function_name(parameters) {
JavaScript statements;
}
To call a function
function_name(parameters);
/* or */
var x = function_name(parameters);
Passing values to a function
- To pass a value to a function, you simply put it in the parentheses after the function: i.e.
myFunction(parameter1, parameter2, ...)
These are called parameters. - You can have any number of parameters for a function (including 0).
- When passing parameters, you may use a variable name or an actual value (i.e.
myFunction(count, 10)
- The function definition must include variable names for each parameter that is passed to it. (i.e.
myFunction(param1, param2, ...)
- The number of parameters in the function definition must match the number of parameters in the function call statement.
- If variables are passed to a function, the names of the variables in the function call statement do not have to match the parameter variables in the function definition. Values are passed based on the sequence of the parameters, so the first parameter in the call statement will be assigned to the first parameter of the function definition regardless of their names.
Returning values from a function
- To return a value to a function, you simply add a return statement to the function with a value:
return var1;
- To be able to use the value returned, you must assign the function call to a variable:
ans = myFunction(param1, param2);
- You can return a literal value, a variable or an expression.
- Only one value can be returned from a function
Example of a function that receives and returns values.
function calcAvg(val1, val2, val3) {
avg = (val1 + val2 + val3) / 3;
return avg;
}
ans = calcAvg(10, 20, 30);
The function has 3 parameters: val1, val2, and val3. When we called the function, we passed it the numbers 10, 20 and 30. This assigned val1 a value of 10, val2 a value of 20 and val3 a value of 30. The function calculated the avg (10 + 20 + 30) / 3 which equals 20 which it stored the avg variable. This value was returned to the calling statement so that at the end of the statement, the variable ans would equal 20.
Variable Scope
There are 2 types of variables in JavaScript. Global variables are available to all parts of a script including the main part of the script and all functions. Local (block level scope) variables are available only within the function.
- Any variable created in the main part of a script (not inside a function) is a global variable.
- A variable created inside a function without using the var keyword will be a global variable.
- A variable created inside a function using the var keyword will be a local variable.
- Function parameters are always local variables.
- If a global variable and a local variable have the same name, the local variable will take precedence over the global variable within the function.
Built-in Functions
The functions shown above are custom or user-defined functions. These are innumerable because there are as many of these as can be imagined. There are some built-in functions used in JavaScript as well. These are JavaScript methods. These methods are functions that are designed to be used on certain objects and there are a host of objects. There are methods for the document object like document.getElementById('idName');
. The getEementById('idName')
method is used as a selector to reference a specific document object by id. The id is written into the html using id="idName"
. There are methods for strings, numbers, dates and just about any other object in JavaScript. JavaScript methods are used to perform actions on objects like getting their values or modifying them in some way.