Functions Flashcards
1
Q
Ways to create functions
A
5 Ways
- Function Declarations
- Function Expressions
- Function Constructor
- Fat Array Functions
- Method Definitions
2
Q
Function Declarations
A
- functions are statements
- cannot be anonymous
- are hoisted
- can reference function inside (and outside) body using function name
3
Q
Function Expressions
A
- var func = function() { }
- is not hoisted
- if named, can reference function inside body (but not outside) using function name
4
Q
Function constructor
A
- the native Function constructor can be used to create function
- functions created with constructor do not have access to closure
- this approach is strongly discouraged
Syntax
- var myFunct = new Function(‘arg1’, ‘arg2,’ ‘body’);
- The first n-args becomes the names of the params of the new function
- And the ‘body’ string becomes the body of the function
5
Q
Fat Arrow Functions
A
- shorter syntax for making functions
- must be anonymous
- this binding is determined by value of this in enclosing execution context, NOT by invoking function
- cannot be used as a constructor
- do not have access to an arguments variable
Syntax
- (x, y) => {
x = x + y;
return x;
}
// If function only has 1 statement, we can remove brackets and return keyword
(x, y) => x
// If function only has 1 argument, we can remove the parens
y => x
6
Q
Method Definitions
A
- a shorter way of writing methods
- created as methods in objects or in classes
- cannot be used as constructors
- var obj = {
myFunc: function( ) { },
myFunc2( ) { }
}