출처 : Node.js 교과서 개정 2판
복습
함수 function()
function을 사용해서 반환하고 return문을 사용함
function() {
return x
}
여기서 x에 원하는 값을 수식을 입력 할 수 있다.
함수를 선언하는 방식은 여러가지이며 주로 화살표 함수라고 부른다.
1. function add1 (x,y) {};
2. const add2 = (x,y) => {};
3. const add3 = (x,y) => {x,y}
문자열 String
문자열을 이어 붙이는 방법
숫자 타입과 문자 타입을 더하면 + 문자열로 된다.
문자열을 더하는 방법은 두가지이다.
1. + 연산자 사용
2. ${문자열 변수명} 사용 이때, + 연산자는 사용하지 않는다.
배열 Array[]
두가지 타입이 있다.
1. let A = new array('1','2'...)
2. const A = ['1','2'...]
권장하는 방법 2번째 const 혹은 대괄호 []를 사용하는 방법이다.
✅ 배열 생성/결합 관련
concat() | 두 배열을 합침 (원본 유지) |
flat() | 다차원 배열을 평탄화 |
join() | 배열을 문자열로 변환 (['a','b'].join(',') → 'a,b') |
Array.from() | 유사 배열이나 iterable 객체를 배열로 만듦 |
Array.of() | 전달된 인자를 배열로 생성 |
2.1.1 const, let
var 대신 사용하는 변수 선언 키워드
- const: 변경 불가능한 상수 선언
- let: 변경 가능한 변수 선언
const name = 'Tom';
// name = 'Jerry'; // ❌ 오류: const는 재할당 불가
let age = 20;
age = 21; // ✅ 가능
2.1.2 템플릿 문자열 (Template Literals)
백틱(`)을 사용해 문자열 안에 변수나 표현식을 간편하게 넣는 문법
const name = 'Alice';
const greeting = `Hello, ${name}!`;
console.log(greeting); // "Hello, Alice!"
2.1.3 객체 리터럴 개선 (Object Literal Shorthand)
변수명과 키가 같을 때 생략 가능
const name = 'Doe';
const age = 25;
const person = {
name, // name: name
age , // age: age
greet() {
console.log(`Hi, I'm ${this.name}`);
}
};
person.greet(); // Hi, I'm Doe
2.1.4 화살표 함수 (Arrow Functions)
간결한 함수 표현 + this 바인딩 유지
// 일반 함수
function add (a, b) {
return a + b;
}
// 화살표 함수
const AddArrow = (a, b) => a + b;
console.log(addArrow(3, 5)); //8
2.1.5 구조 분해 할당 (Destructuring)
배열이나 객체에서 값을 쉽게 꺼낼 수 있음
// 배열 구조 분해
const arr = [1, 2, 3];
const [first, second] = arr;
console.log(first, second); // 1 2
// 객체 구조 분해
const user = {name : 'Tom', age : 30 };
const {name, age } = user;
console.log(name, age); // Tom 30
2.1.6 클래스 (Class)
객체 지향 프로그래밍을 위한 문법
class Animal {
contructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
const dog = new Animal('Dog');
dog.speak(); // Dog makes a sound.
2.1.7 프로미스 (Promise)
비동기 작업을 처리하는 객체
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('데이터 로드 완료!');
}, 1000);
)};
};
fetchData().then(result => {
console.log(result); // 데이터 로드 완료!
});
2.1.8 async/await
Promise를 더 간결하게 처리하는 비동기 문법
const fetchData = () => {
return new Promise(resolve => {
setTimeout(() => resolve('✅ 완료'), 1000);
});
};
const load = async () => {
const result = await fetchData();
console.log(result); // ✅ 완료
};
load();
2.1.9 Map / Set
새로운 컬렉션 타입
// Map : 키-값 저장소
const map = new Map();
map.set('name', 'Tom');
console.log(map.get('name)); //Tom
// Set : 중복 없는 값의 집합
const set = new Set();
set.add(1);
set.add(1); // 중복처리되어 무시
set.add(2);
console.log(set); // set(2) {1, 2}
2.1.10 널 병합 연산자 / 옵셔널 체이닝
- ES2020에서 추가된 (널 병합(nullish coalescing)) 연산자와 ?.(옵셔널 체이닝(optional chaining)) 연산자입니다.
- 널 병합 연산자는 주로 || 연산자 대용으로 사용되며, falsy 값(0, '', false, NaN, null, undefined) 중 null과 undefined만 따로 구분합니다.
const a = 0;
const b = a || 3; // || 연산자는 falsy 값이면 뒤로 넘어감
console.log(b); // 3
const c = 0;
const d = c ?? 3; // ?? 연산자는 null과 undefined일 때만 뒤로 넘어감
console.log(d); // 0;
const e = null;
const f = e ?? 3;
console.log(f); // 3;
const g = undefined;
const h = g ?? 3;
console.log(h); // 3;
옵셔널 체이닝 연산자는 null이나 undefined의 속성을 조회하는 경우 에러가 발생하는 것을 막습니다.
const a = {}
a.b; // a가 객체이므로 문제없음
const c = null;
try {
c.d;
} catch (e) {
console.error(e); // TypeError: Cannot read properties of null (reading 'd')
}
c?.d; // 문제없음
try {
c.f();
} catch (e) {
console.error(e); // TypeError: Cannot read properties of null (reading 'f')
}
c?.f(); // 문제없음
try {
c[0];
} catch (e) {
console.error(e); // TypeError: Cannot read properties of null (reading '0')
}
c?.[0]; // 문제없음
2.2.1 AJAX (Asynchronous JavaScript and XML)
페이지 전체를 새로고침하지 않고 서버와 데이터를 주고받는 기술. 요즘은 XMLHttpRequest보다는 fetch()를 더 많이 씀.
// 예: JSONPlaceholder에서 유저 정보 받아오기
fetch('https://jsonplaceholder.typicode.com/users/1')
.then(response => response.json())
.then(data => {
console.log(data.name); // Leanne Graham
})
.catch(error => {
console.error('에러 발생:', error);
});
📌 fetch()는 기본적으로 Promise를 반환하므로 then, catch 또는 async/await로 사용 가능해.
2.2.2 FormData
HTML 폼 데이터를 쉽게 수집하고, 서버로 전송하기 위한 객체
<form id="myForm">
<input type="text" name="username" value="Tom">
<input type="file" name="file">
<button type="submit">전송</button>
</form>
<script>
const form = document.getElementById('myForm');
form.addEventListener('submit', function (e) {
e.preventDefault(); // 새로고침 방지
const formData = new FormData(form);
fetch('/upload', {
method: 'POST',
body: formData,
})
.then(res => res.text())
.then(result => {
console.log('서버 응답:', result);
});
});
</script>
📌 파일 업로드도 자동 처리됨! (Content-Type은 브라우저가 알아서 multipart/form-data로 설정함)
.2.3 encodeURIComponent, decodeURIComponent
URL에서 사용할 수 없는 문자들을 안전하게 인코딩/디코딩하는 함수
const keyword = "안녕? 만나서 반가워!";
const encoded = encodeURIComponent(keyword);
console.log(encoded); // %EC%95%88%EB%85%95%3F%20%EB%A7%8C%EB%82%98%EC%84%9C%20%EB%B0%98%EA%B0%80%EC%9B%8C%21
const url = `https://example.com/search?query=${encoded}`;
console.log(url);
// 디코딩
const decoded = decodeURIComponent(encoded);
console.log(decoded); // 안녕? 만나서 반가워!
📌 encodeURIComponent()은 개별 파라미터 값에만 사용해야 함. 전체 URL에 쓰면 안됨!
2.2.4 데이터 속성과 dataset
HTML 요소에 data-로 시작하는 속성을 지정하면 JavaScript에서 dataset을 통해 접근 가능
✅ 예시: 버튼에 데이터 속성 넣기
<button id="btn" data-user-id="123" data-role="admin">
유저 정보
</button>
<script>
const btn = document.getElementById('btn');
btn.addEventListener('click', function () {
const userId = this.dataset.userId;
const role = this.dataset.role;
console.log(`유저 ID: ${userId}, 권한: ${role}`); // 유저 ID: 123, 권한: admin
});
</script>
📌 dataset은 camelCase로 접근해야 해 (예: data-user-id → dataset.userId)
'node.js' 카테고리의 다른 글
InfluxDB, Redis, MQTT 정리 (0) | 2025.04.18 |
---|---|
관계형 데이터 RDB 기초 정리 (0) | 2025.04.11 |
express 에러 코드 정리 (0) | 2025.04.10 |
2025-04-09 익스프레스 실습(로그인, 회원가입) (0) | 2025.04.09 |
multer (0) | 2025.04.09 |