Javascript: Function Syntax
Funct
/**
* Function as Declarations
*/
function square(a) {
return a * a;
}
/**
* Anonymous Function as Expressions
*/
let square = function (a) { return a * a; }
/**
* Arrow Function as Expressions
*/
let square = (a) => { return a * a }
/**
* Arrow Function as Expressions
* The parentheses that define function argument and
* curly braces that define function statement could be omitted,
* only if there is one argument and one statement exist.
* This expression return on execution by default,
* so you could omit `return` keyword too.
*/
let square = a => a * a
/**
* Anonymous Function as Immediately-Invoked Function Expressions
* The first pair of parentheses define function expression.
* The last pair of parentheses invoke the function.
* You could place argument value inside the trailing parentheses.
*/
(function(a) {
return a * a;
})()
/**
* Anonymous Function as Immediately-Invoked Function Expressions
* The first parentheses that define function argument could be omitted,
* only if there is one unary operator exist.
*/
+function (a) {
return a * a;
}();
-function (a) {
return a * a;
}();
!function (a) {
return a * a;
}();
~function (a) {
return a * a;
}();
void function (a) {
return a * a;
}();
/**
* Arrow Function as Immediately-Invoked Function Expressions
* The first pair of parentheses define function expression.
* The last pair of parentheses invoke the function.
* You could place argument value there.
*/
(a => a * a)()
Hindari menggunakan iife untuk mendapatkan function scope.
for (var i = 1; i <= 5; i++) {
void function (step) {
setTimeout(function() {
console.log('I reached level ' + step);
}, 1000 * i);
}(i);
}
Gunakan variable scope saja!
for (let i = 1; i <= 5; i++) {
setTimeout(function () {
console.log('I reached level ' + i);
}, 1000 * i);
}