Definition Expressions
You've already seen the basic way to declare a function, but there's another way that's pretty common called a Definition Expressions.
Declaration/Invocation
const $ = document.querySelector.bind(document)
function add(a, b) {
const c = a + b;
return c;
}
const output = add(2, 2)
$('#output').innerHTML = output
console.log(output)
This is what we did in the last video, it's the classic declaration/invocation pattern.
Because we're using a return statement inside the function.
We can use an assignment to invoke the function.
Standalone Invocation
const $ = document.querySelector.bind(document)
function add(a, b) {
const c = a + b;
$('#output').innerHTML = c
console.log(c)
}
add(2, 2)
It's not necessary to make an assignment in order to call a function.
So here, I'm adding the output statements directly inside the function declaration.
That way we don't need to use an assignment and can just call the function directly.
Definition Expression
const $ = document.querySelector.bind(document)
let add = function(a, b) {
const c = a + b;
$('#output').innerHTML = c
console.log(c)
}
add(2, 2); //4
add(4, 4); //8
There's another way to work with functions, it's called a definition expression and is a combination of what we've been doing.
In JavaScript, you can always assign a sequence of commands to a variable or a constant like this. Those commands are know as expressions. What's special here is that I'm using a function as an expression.
Notice that in this case, the function has no name...although there wouldn't be a problem for it to have a name here, but it's no necessary. This is known as an anonymous function.
In this case, you still have to call the function, but now, you can use the add variable pretty much like the function call...and that means that we can call this add definition expression multiple times.
It's IIFE
(function(a, b) {
const $ = document.querySelector.bind(document)
const c = a + b;
$('#output').innerHTML = c
console.log(c)
})(2, 2);
Let's take a look at another pattern. This one has a great name...it's know as an IIFE., which stands for an Immediately Invoked Function Expression.
An IIFE is a function expression that will run right away because we're immediately calling...or invoking it.
They used to be more popular in the past and I haven't used one in a while, but it's one of those things that will help you understand functions better, so let's try it.
Here we have an anonymous function wrapped around parenthesis. The parenthesis allows us to create a group out of the function. This is what makes the entire function an expression.
The second part, which is at the bottom is invoking the function...passing it along some parameters.
I think you'll want to try this, so let's see if we can convert one of our previous functions into an IIFE.