input, output
함수 선언문
function add(매개변수) {
//함수 내부에서 실행할 로직
}
두 개의 숫자를 입력 받아서 덧셈을 한 후 내보내는 함수
function add(x, y) {
return x + y;
}
함수 표현식
let add2 = function (x, y) {
return x + y;
}
함수를 호출한다(= 사용한다)
함수명() -> add()
console.log(add2(10, 20));
let functionResult = add2(20,30);
console.log(functionResult);
input : 함수의 input -> 매개변수(매개체가 되는 변수!)
output : return문 뒤에 오는 값 : 반환값
let x = 10;
function printX() {
console.log(x);
}
console.log(x);
printX();
function printX() {
let x = 10;
console.log(x);
}
console.log(x);
printX();
ES6 신 문법
function add(x, y) {
return x + y;
}
기본적인 화살표 함수
let arrowFunc01 = (x, y) => {
return x + y;
}
한 줄로 작성시
let arrowFunc02 = (x, y) => x + y;
화살표 함수로!
let arrowFunc03 = x => x;
조건문 - if, else if, else, switch
if문
let x = 10;
if (x > 0) {
console.log("x는 양수입니다.")
}
y의 길이가 5보다 크거나 같으면 길이를 console.log로 출력해보자
let y = "hello world";
if (y.length >= 5) {
console.log("y가 더커요")
}
if - else문
if (x > 0) {
// main logic #1
console.log("x는 0보다 큽니다")
} else {
// main logic #2
console.log("x는 0보다 작습니다")
}
if - else if - else 문
let a = 10;
if (a < 0) {
// main logic #1
console.log(1)
} else if (a >= 0 && x < 10) {
// main logic #2
console.log(2)
} else {
// main logic #3
console.log(3)
}
switch
변수의 값에 따라, 여러 개의 경우(case) 중 하나를 선택
let fruit = "사과";
switch (fruit) {
case "사과":
console.log("사과입니다.");
break
case "바나나":
console.log("바나나.");
break
case "키위":
console.log("키위입니다.");
break
default:
console.log("아무것도 아닙니다.");
break
}
let age = 20;
let gender = "여성";
// 미성년자 구분예시
if (age >= 18) {
if (gender === "여성") {
console.log("성인 여성입니다.");
} else {
console.log("성인 남성입니다.");
}
} else {
if (gender === "여성") {
console.log("미성년 여성입니다.");
} else {
console.log("미성년 남성입니다.");
}
}
이번 TIL도 JS문법 중점이다.
배운 문법을 정리하면서 작성을 하니 자연스럽게 외워지는 것 같다.
특히나 함수는 중요하다고 하니 계속 코드 작성을 해봐야 겠다.
잘보고 갑니다 :)