Animations
API
Arrays
Async
Basics
Challenges
Classes
Console
Dates
Debugging
DOM Elements
DOM Methods
DOM Properties
Event Listeners
Flow Control
Forms
Functions
Global Functions
JSON
Keywords
Libraries (3rd party)
Math
Modules
Objects
Snippets
String
Types
Widgets
Window Object
Expanding on the anonymous function concept, we know that
function do not need names. You can also take function, not give it a name, and "express" it with a lambda expression.
Take this code snippet for example - this is using a function with a name called DoMath
:
let a = 100;
let b = 100;
function DoMath(a,b)
{
return a+b;
}
$("#Demo1").html(DoMath(a,b));
Here's the same thing and assigning the function to a variable called do math. This is how we invoke the function. The function itself has no name.
$(function ()
{
let c = 101;
let d = 101;
let DoMath2 = function(c,d) {return c+d;};
$("#Demo2").html(DoMath2(c,d));
});
Now we can use an function expression. Notice how I said "sum is an arrow, that takes two args and it's return is e + f "?
This a function expression - aka an arrow function. The expression is assigned to a variable called sum
.
$(function ()
{
let e = 102;
let f = 102;
let sum = (e,f) => { return e + f; };
$("#Demo3").html(sum(e,f));
});
We can even go one step further and remove return
and the curly braces.
$(function ()
{
let g = 103;
let h = 103;
let sum = (g,h) => g + h;
$("#Demo4").html(sum(g,h));
});