종우의 컴퓨터 공간
Function Declarations & Expressions 본문
자바 스크립트 (JavaScript)/JavaScript Language Fundamentals
Function Declarations & Expressions
종우공간 2021. 7. 28. 08:41Function Declarations
function greet(firstName = 'John', lastName = 'Doe') {
return 'Hello ' + firstName + ' ' + lastName;
}
console.log(greet('James', 'Lim')); // yields 'Hello James Lim'
console.log(greet()); // yields 'Hello John Doe'
- 자바스크립트에서는 함수에서 return type, parameter type을 명시하지 않는다.
- parameter의 default 값을 설정하는 방법은 위의 예제처럼 '<paramter> = <value>' 형식으로 지정한다.
- use it when you want to create a function on the global scope and make it available throughout your code
Function Expressions
const square = function(x = 3) { // default is 3
return x*x;
};
console.log(square(4)); //yields 16
console.log(square()); //yields 9(default)
- 함수를 변수로 저장하는 방법이다.
- function declaration과 다른 점은 여기서의 function은 이름이 보통 없다는 것이다. (anonymous function)
- use it when you want to limit where the function is available, keep your global scope light, and maintain clean syntax
Immediately Invocable Function Expressions(AKA, IIFEs)
(function() {
console.log('IIFE Ran..');
})();
(function(name) {
console.log(name);
})('James');
- Module 패턴과 같은 디자인 패턴에서 많이 사용된다.
- 함수를 선언하고 바로 사용한다.
Property Method
const todo = {
add: function() {
console.log('Add todo...');
},
edit: function(id) {
console.log(`Edit todo ${id}`);
}
}
todo.delete = function() {
console.log('Delete todo...')
}
todo.add();
todo.edit(22);
todo.delete();
'자바 스크립트 (JavaScript) > JavaScript Language Fundamentals' 카테고리의 다른 글
Window Objects (0) | 2021.07.30 |
---|---|
General loops (0) | 2021.07.30 |
Switch Statement (0) | 2021.07.28 |
If Statements & Comparison Operators (0) | 2021.07.25 |
Dates & Times (0) | 2021.07.25 |