Functions: Reusable Blocks of Code
Odin status: in the page JS Foundations fundamental part 3. Current reading: 6. Call Stack.
- Function
- A piece of code that does a single task inside a define block.
- Parentheses
() - Functions using parentheses
()to encapsulate their block code. - Some common built-in language structure are using
()as well. These are not functions. For examples:forloopwhileordo...whileloopif...elsestatement
- Built-in browser functions
- Examples
myText.replace("dog", "cat")myArray.join(' ')Math.random()alert(message)prompt(message, default)confirm(question)
- Methods vs functions
- Methods are functions that are part of objects
- Custom functions
- Functions we defined ourselves in our code. Not inside the browser.
- Function declaration
function myFunction() {...code...};- Invoking functions
- Invoke = run, activate
myFunction();- Function parameters
- Function parameters: variable values needed to be passed into the function block.
- Written within the parentheses
()and comma separated - Example of function that doesn't require parameter:
Math.random() - Example of function that needs parameter:
replace("original", "replacement") -
- Parameters vs arguments
-
- Function declaration: Parameters are the variables listed.
- Calling a function: Arguments are the values passed.
-
function func (param1, param2) { codeblock; } func (arg1, arg2);
- Optional parameters
- Sometimes parameters are optional. When it is not specified, it wil typically adopt some kind of default behaviour.
- For example, function
join(). Without defined parameters comma separator is used. - Default parameters
-
- Optional parameters in a custom function can be made by defining default parameter using an equal mark
=when defining the function. -
Function declaration:
function myFunction(name="Kitten") {console.log(`Hello, ${name}!`)}; -
Function invoke:
myFunction();// "Hello, Kitten!"
myFunction("Ruby");// "Hello, Ruby!" - Alternatively, default can be generated inside the code block.
function myFunction(name) { if (name === undefined) {name = "Kitten";} console.log(`Hello, ${name}!`); } myFunction(); // "Hello, Kitten!" - Using or operator
||function myFunction(name) { name = name || "Kitten"; console.log(`Hello, ${name}!`); } myFunction(); // "Hello, Kitten!"
- Optional parameters in a custom function can be made by defining default parameter using an equal mark
- Anonymous functions
- Functions without function name
function () {alert("Hello!");}- Often used in the case where a function receives another function as a parameter.
- Example:
addEventListener()function -
- Anonymous function example:
addEventListener() - This function is used with 2 parameters:
- First parameter: event name. For example:
"keydown" - Second parameter: function triggered upon event happens. For example:
myFunction
- First parameter: event name. For example:
- Without anonymous function:
function myFunction (event) {output.textContent = `You pressed "${event.key}".`);}textBox.addEventListener("keydown", myFunction);
- With anonymous function:
textBox.addEventListener("keydown", function(event) {output.textContent = `You pressed "${event.key}".`);});
- Anonymous function example:
- Arrow function
-
- Instead of:
function(event) {...codeblock...} - You can write:
(event) => {...codeblock...} - If there's only 1 parameter, you can omit parameter's bracket:
event => {...codeblock...} - If there's only 1 line of codeblock, you can omit the curly brackets:
event => ...codeblock... - If the function needs to return a value and only contains 1 line, you can omit the
returnstatement.function doubleItem(item) {return item * 2;}item => item * 2const original = [1, 2, 3];const doubled = original.map(item => item * 2);console.log(doubled); // [2, 4, 6]
- Instead of:
-
- Keydown example above can be written as:
-
textBox.addEventListener("keydown", (event) => {output.textContent = `You pressed "${event.key}".`);});textBox.addEventListener("keydown", event => {output.textContent = `You pressed "${event.key}".`);});textBox.addEventListener("keydown", event => output.textContent = `You pressed "${event.key}".`);
- Variable scopes
- Where a variable can be seen from.
-
- Global scope
- Top level outside all functions.
- Variables are accessible from everywhere in the code.
- Function scope
- Variables can only be seen inside function where it is declared.
- Loop and conditional scope
- They are not really functions even though sharing similar bracketing. The same scoping rules doesn't apply.
- Naming a function
-
- Function is an action. So the names are usually verb. Keep it brief and accurate. Decribe what the function does.
- 2 words name in camelCase is common. First word is a verb, second is a noun.
- Some common first words and their common uses:
get– return a valuecalc– calculate somethingcreate– create somethingcheck– check something and return a booleanis– is it true or false
- Examples:
showMessage– shows a messagegetAge– returns the age (gets it somehow)calcSum– calculates a sum and returns the resultcreateForm– creates a form (and usually returns it)checkPermission– checks a permission, returns true/falseisPrime– checking a value is a prime or not. Return boolean.
- One function one action
-
- Limit 1 action per function. When there are 2 actions, better separate them in 2 functions. A third function can be created to combine them.
- For example:
getAge– Let the function only get the age. Don't have it shows an alert of the age.checkPermission– Should only check the permission and return the result. Don't mix it with displaying messageAccess granted/denied