널 병합 연산자는 null 또는 undefined일 때만 기본값을 반환한다.
// null 또는 undefined일 때 기본값 반환
const text = null;
const data = text ?? "hello world";
console.log(data); // "hello world"
// 값이 있으면 그 값을 반환
const text2 = "king";
const data2 = text2 ?? "hello world";
console.log(data2); // "king"
// 기존 방식
function printTitle(text) {
let title = text;
if(text == null || text == undefined) {
title = "hello world";
}
console.log(title);
}
// ?? 연산자 사용
function printTitle2(text) {
let title = text ?? "hello world";
console.log(title);
}
printTitle2("greeting"); // "greeting"
printTitle2(); // "hello world"
function getCount(count) {
return count || 'There is no record';
}
// OR 연산자는 falsy 값(0, '', null, undefined, NaN)을 모두 처리
console.log(getCount(0)); // 'There is no record' (0도 false로 처리)
console.log(getCount(1)); // 1
// 반면 ?? 연산자는 null과 undefined만 처리
function getCount2(count) {
return count ?? 'There is no record';
}
console.log(getCount2(0)); // 0 (0은 유효한 값으로 인정)
console.log(getCount2(null)); // 'There is no record'
| 입력값 | ` | |
|---|---|---|
| 5 | 5 | 5 |
| 0 | "There is no record" | 0 |
| undefined | "There is no record" | "There is no record" |
| "" | "There is no record" | "" |
| null | "There is no record" | "There is no record" |
JavaScript 객체 표기법(JSON)을 사용한 데이터 구조화 방법이다.
// 빈 객체 생성
let Member = {};
console.log(Member); // {}
// 속성 추가
Member.name = "hong";
console.log(Member.name); // "hong"
Member.age = 100;
// 메서드 추가
Member.print = function() {
document.write("<br>" + this.name + " / " + this.age + "<br>");
}
Member.print(); // "hong / 100"
const grade = {
"list": {"hong": 10, "kim": 20, "park": 30},
"show": function() {
for(let key in this.list) {
document.write(key + " : " + this.list[key] + "<br>");
}
}
};
grade.show();
// hong : 10
// kim : 20
// park : 30
let arr = ["A", "B", "C"];
// for...in: 인덱스(키)를 반환
for(let index in arr) {
console.log(arr[index]); // "A", "B", "C"
}
// for...of: 값을 직접 반환 (ES6)
for(let value of arr) {
console.log(value); // "A", "B", "C"
}
let students = [];
students.push({"이름": "홍길동", "국어": 80, "영어": 90});
students.push({"이름": "아무개", "국어": 10, "영어": 50});
students.push({"이름": "이순신", "국어": 70, "영어": 90});
// [{}, {}, {}] 구조
for(let index in students) {
console.log(
students[index],
students[index].이름,
students[index].국어
);
}
let myCars = {
"name": "john",
"age": 30,
"cars": [
{"name": "Ford", "model": ["Mustang", "Focus"]},
{"name": "Bmw", "model": ["520", "x5", "x7"]},
{"name": "Fiat", "model": ["500", "Panda"]}
]
};
// 차량 이름과 모델 출력
for(let obj of myCars.cars) {
document.write("차량이름: " + obj.name);
for(let index in obj.model) {
document.write(" " + obj.model[index]);
}
document.write("<hr>");
}
// 차량이름: Ford Mustang Focus
// 차량이름: Bmw 520 x5 x7
// 차량이름: Fiat 500 Panda
배열을 다루는 강력한 메서드들이다. 특히 map()과 filter()는 React에서 자주 사용된다.
const numbers = [45, 5, 9, 46, 25];
function myFunc2(value, index, array) {
console.log(value, index, array);
}
// forEach는 배열의 개수만큼 콜백 함수를 호출
numbers.forEach(myFunc2);
// map은 기존 배열을 변환하여 새로운 배열 생성
const numbers2 = [65, 44, 85, 7];
const newArray = numbers2.map(function(value, index, array) {
return value * 10 + index;
});
console.log(newArray); // [650, 441, 1702, 73]
// 화살표 함수로 간결하게
let evens = [2, 4, 6, 8];
let odds = evens.map(value => value + 1);
console.log("odds:", odds); // [3, 5, 7, 9]
let data = [2, 5, 6, 9];
// 짝수만 필터링
let filterData = data.filter(number => number % 2 === 0);
console.log("filterData", filterData); // [2, 6]
// 서버에서 받은 사용자 데이터 (axios.get, fetch 등)
const users = [
{name: "홍길동", age: 25},
{name: "김유신", age: 30},
{name: "아무개", age: 10}
];
// 이름만 추출
const nameArray = users.map(user => user.name);
console.log("nameArray", nameArray); // ["홍길동", "김유신", "아무개"]
// 짝수/홀수 판별
const numbers3 = [1, 2, 3, 4, 5];
const dataList = numbers3.map(number => {
return number % 2 === 0 ? "even" : "odd"
});
console.log(dataList); // ["odd", "even", "odd", "even", "odd"]
// 게시판 데이터
const boards = [
{id: 1, title: "첫번째 글", content: "안녕 방가 방가"},
{id: 2, title: "두번째 글", content: "안녕 점심"},
{id: 3, title: "세번째 글", content: "안녕 저녁"},
{id: 4, title: "네번째 글", content: "안녕 지각 금지"}
];
// id가 2인 글을 삭제 (filter로 제외)
const deleteBoardId = (boards, deleteId) => {
return boards.filter(board => board.id !== deleteId);
};
const newBoardList = deleteBoardId(boards, 2);
console.log(newBoardList);
// [{id: 1, ...}, {id: 3, ...}, {id: 4, ...}]
// JSON 문자열로 변환
console.log("data " + JSON.stringify(newBoardList));
참고: React에서는 map()으로 데이터를 추가하고, filter()로 데이터를 삭제한다. Vue에서는 v-for 디렉티브를 사용한다.
코드를 재사용 가능한 모듈로 분리하여 관리한다.
<!-- 기존 방식: 전역 스코프 충돌 문제 -->
<script src="a.js"></script>
<script src="b.js"></script>
<script>
// a.js와 b.js에 같은 이름의 변수가 있으면 충돌 (overwrite)
const data = getTotal();
console.log(data); // 예상과 다른 값이 나올 수 있음
</script>
<!-- type="module"로 모듈 시스템 사용 -->
<body>
<script type="module" src="./app.js"></script>
<script type="module" src="./app2.js"></script>
</body>
// data.js - 여러 개를 export
export const pi = 3.14;
export function sum(a, b) {
return a + b;
}
// main.js - 중괄호로 import
import {pi, sum} from './data.js';
console.log(pi); // 3.14
const data = sum(10, 20);
console.log("data : " + data); // 30
// data2.js - 1개만 내보낼 때
const message = "Hello World";
export default message;
// main.js - 중괄호 없이 import
import message from './data2.js'; // 중괄호 사용 안 함
console.log(message);
중요:
{} 필수{} 사용하면 안 됨document.getElementById("myAnchor").addEventListener("click", function(event) {
// a 태그의 기본 동작(href 이동)을 막는다
event.preventDefault();
alert("hello world");
});
const btn = document.querySelector(".btn");
btn.addEventListener('click', function(e) {
console.log(this); // <button class="btn">Button</button>
console.log(e.currentTarget); // <button class="btn">Button</button>
console.log(this === e.currentTarget); // true
});
참고: 화살표 함수에서 this는 다른 의미를 가지므로 주의해야 한다.
ancestor.addEventListener("click", (e) => {
e.stopPropagation(); // 이벤트 버블링 방지
console.log('ancestor');
});
<button onclick="alert('Hello')">클릭</button>
<script>
function greet() {
alert('Hello');
}
</script>
<script src="./script.js"></script>
./ : 현재 디렉토리 (상대경로)../ : 상위 디렉토리 (부모 디렉토리)/ : 루트 디렉토리 (절대경로)http:// : 외부 URL (예: CDN)ES6는 JavaScript를 더욱 강력하고 편리하게 만들어주는 문법들을 제공한다. 특히 화살표 함수, 구조 분해 할당, Spread 연산자, 모듈 시스템은 현대 프론트엔드 개발(React, Vue)에서 필수적으로 사용되는 기능들이다.
학습 팁: