Funtion Flashcards
WHAT TYPE OF FUNCTION?
function isEven(num) { return num % 2 === 0; } isEven(24); // => true isEven(11); // => false
FUNCTION declaration
what are the 6 types of functions?
Function declaration Function expression Shorthand method definition Arrow function Generator function Function constructor
console.log(typeof hello); // => function hello(name) { return `Hello ${name}!`; }
‘function’
console.log(hello.name) // => function hello(name) { return `Hello ${name}!`; }
‘hello’
function hello(name) { return `Hello ${name}!`; } console.log(hello('Aliens')); // =>
‘Hello Aliens!’
WHAT TYPE OF FUNCTION?
function sum(a, b) { return a + b; } sum(5, 6); // => 11 ([3, 7]).reduce(sum) // => 10
A regular function
_______means that you declare the function once and later invoke it in many different places.
Regular function
the _________ in a statement always starts with the keyword function.
function declaration
WHAT TYPE OF FUNCTION?
var isTruthy = function(value) { return !!value; };
function expression
(function() { 'use strict'; if (true) { function ok() { return 'true ok'; } } else { function ok() { return 'false ok'; } } console.log(typeof ok === 'undefined'); // =>
true
(function() { 'use strict'; if (true) { function ok() { return 'true ok'; } } else { function ok() { return 'false ok'; } }
console.log(ok()); //
})();
Throws “ReferenceError: ok is not defined”
because the function declaration is inside a conditional block.
(function() { 'use strict'; var ok; if (true) { ok = function() { return 'true ok'; }; } else { ok = function() { return 'false ok'; }; } console.log(typeof ok === 'function'); // =>
})();
true
HOW TO FIX THIS?
(function() { 'use strict'; if (true) { function ok() { return 'true ok'; } } else { function ok() { return 'false ok'; } }
console.log(ok()); // Throws “ReferenceError: ok is not defined”
})();
make “function ok” into a function expression
The 3 things a function expression creates a function object that can be used in different situations:
- Assigned to a variable as an object count = function(…) {…}
- Create a method on an object sum: function() {…}
- Use the function as a callback .reduce(function(…) {…})
var getType = function(variable) { return typeof variable; }; getType.name // =>
empty string
var getType = function funName(variable) { console.log(typeof funName === 'function'); // => true return typeof variable; }
console.log(getType(3)); // =>
‘number’