JS Array Function
Another way to create a function and assign it to a variable (this process is called #Function Expression) is called arrow function, which is similar to Python Lambda Function
let myFun = (para1, para2) => expression
This creates a function myFun
that accepts arguments para1
and para2
, then evaluates the expression
on the right side with their use and returns its result.
In other words, it’s the shorter version of the #Function Expression:
let myFun = function(para1, para2) {
return expression;
};
- If we have only one parameter, then parentheses around parameters can be omitted
- This gives the simplest form of a function:
para => expression
- This gives the simplest form of a function:
- If there are no parameters, parentheses will be empty (but they should be present)
- For more complex expressions, like multiple expressions or statements, we should enclose them in curly braces
{}
, then use a normalreturn
within them
Dynamically Create a Function
let age = prompt("What is your age?", 18);
let welcome = (age < 18) ?
() => alert('Hello') :
() => alert("Greetings!");
welcome();