: 특정 작업을 수행하기 위해 독립적으로 설계된 코드의 집합
= 함수 (선언문)
function helloWorld(){
//함수 정의
// return 키워드 생략 가능 (반환 값이 없을 경우)
console.log('Hello, World!');
}
const sayHello = function hello(){
console.log('hello');
};
sayHello();
//hello(); // referenceError : hello is not defined (같은 스코프에 존재하지 않기 때문)
const helloWorld3 = function () {
// return 생략버전
console.log('Hello, world! 3');
};
helloWorld3();
helloWorld3();
helloWorld3();
function food(text){ // text : 매개변수
return text;
}
console.log(food("제육덮밥")); // 매개변수 : 제육덮밥
function music(name, title){
// return name + ' - ' + title; // name - title
return `${name} - ${title}`; // 백틱 입력방식 => 많이 사용
}
console.log(music('윤도현', '흰수염고래'));
// 이렇게도 가능!
function music2 (name, title){
console.log(`${name} - ${title}`);
}
music2('악뮤', '후라이의 꿈');
// 일반형 (단일 표현식)
// function square(x){
// return x * x;
// }
// console.log(squre(2));
// 축약형
const square1 = (x) => x ** 2 ;
// const square1 = (x) => x * x ; (같음!)
// ** 뒤에 무조건 값(제곱값)을 넣어줘야 함 !
console.log(square1(3));
const square = (x, y) => x * y;
console.log(square(3,4)); //12
// 일반형 (여러줄)
// function triangle(base, height){
// const area = (base * height) /2;
// // area : 변수 base, height: 메개변수 변수에 메개변수 값을 담아서
traingle 함수에서 호출!
// return area;
// }
// 축약형
const triangle = (base, height) => {
const area = (base * height) / 2 ;
return area;
};
함수 표현식 (변수에다가 함수를 넣은것)
// - 호이스팅의 대상이 될 수 없음.
// - Why?
// - 변수에 함수가 할당되기 때문에 그 이후에만 호출 가능!
// sayHello6(); // referuenceError! 변수에 함수를 할당되기 때문에 이전 호출 불가능!
const sayHello6 = () => {
console.log('hello2 ~~~~');
};
sayHello6(); // 이후 호출은 가능!
const sayHello7 = () => console.log('hello2 ~~~~');