JavaScript Functions (Simplified)
Functions are an essential element in Programming anything really, so let's dive into functions, and how they work, specifically in JavaScri
Functions
- At their simplest form, functions are reusable blocks of code
- These blocks of code are essential in DRY code
Functions in Depth
- functions take input (through arguments) and then produce an output
Syntax
function test () {
...
return ...
}
- First, we have to define our function and then name it
- In the parathesis
()
are our parameters- these parameters act as placeholders for our input
- inside the curly brackets we write our actual code that out function will do
- the return keyword would simply return any values produced from the function
- Calling the function
- now that we defined our function, we need to use it in our code, we do that by calling the function
test(...)
- inside the parenthesis () is our arguments, which are the inputs that we want to work with
Example
here is an example of a function that adds 2 numbers// defining our function function add(x, y){ answer = x + y; return answer; } // calling our function add (3, 5);
- inside the parenthesis () is our arguments, which are the inputs that we want to work with
- now that we defined our function, we need to use it in our code, we do that by calling the function
Expression vs Declaration functions
- Declaration of functions are used to create named functions
- Example
function add(x, y){ return x + y
- Example
Function Expressions
- Function expressions are function that are stored inside variables
- These function are anonymous (without a name property)
- Syntax
sum = function(x, y){ return x - y }
Arrow Functions (ES6+)
- By using the arrow notation
=>
we don't require the function keyword to define the function
const sum = (x, y) => {
return x + y;
}
console.log(sum(2,5));
Variations of the Arrow Functions
If we have only 1 parameter to our function, we don't need our parenthesis
const log = x => { console.log (x) }
If we have 1 expression in our function, we can do not need the return keyword
const calcAge = age => 2022 - birthyear
Function Calling other Functions
Lets create a function that would first of all square the 2 arguments provided, then add them
First we need to define the first function that would square the 2 arguments
function square(x) { const y = x ** 2; return y; }
Second we would call the function inside the function that would add the 2 squares
function square(x) { const y = x ** 2; return y; } function sumOfSquares(x, y) { const a = square(x); const b = square(y); return a + b; }
Finally we log the value of the function inside the console
console.log(sumOfSquares(2, 3));