변수 선언과 스코프
자바스크립트에서는 var, let, const를 사용하여 변수를 선언합니다. 현대적인 개발에서는 블록 스코프를 지원하는 let과 const를 주로 사용합니다.
| 특성 | var | let | const |
|---|---|---|---|
| 스코프 | 함수 스코프 | 블록 스코프 | 블록 스코프 |
| 호이스팅 | undefined로 초기화 | TDZ (일시적 사각지대) | TDZ (일시적 사각지대) |
| 중복 선언 | 가능 | 불가능 | 불가능 |
| 값 재할당 | 가능 | 가능 | 불가능 |
데이터 타입 및 타입 확인
자바스크립트의 데이터 타입은 원시 타입(Number, String, Boolean, Undefined, Null, Symbol, BigInt)과 객체 타입(Object, Array, Function 등)으로 나뉩니다.
const checkTypes = () => {
console.log(typeof 42); // 'number'
console.log(typeof 'hello'); // 'string'
console.log(typeof undefined); // 'undefined'
console.log(typeof null); // 'object' (역사적 버그)
console.log(typeof {}); // 'object'
// 배열 및 객체 정확한 판별
console.log(Array.isArray([1, 2])); // true
console.log(Object.prototype.toString.call([])); // '[object Array]'
};
입출력 및 연산자
데이터를 입력받고 출력하는 기본적인 방법과 다양한 연산자를 활용합니다.
- 입력:
prompt('메시지 입력') - 출력:
console.log(),alert(),document.write() - 비교 연산자:
==(동등),===(일치),!=,>,< - 논리 연산자:
&&(AND),||(OR),!(NOT)
제어문 (조건 및 반복)
조건문
const userRole = 'admin';
if (userRole === 'admin') {
console.log('관리자 권한');
} else if (userRole === 'editor') {
console.log('편집자 권한');
} else {
console.log('일반 사용자');
}
const statusCode = 200;
switch (statusCode) {
case 200:
console.log('OK');
break;
case 404:
console.log('Not Found');
break;
default:
console.log('Unknown Error');
}
반복문
// 기본 for 문
for (let index = 0; index < 5; index++) {
console.log(`Index: ${index}`);
}
// 객체 키 순회
const config = { theme: 'dark', lang: 'ko' };
for (let key in config) {
console.log(`${key}: ${config[key]}`);
}
// 배열 값 순회
const colors = ['red', 'green', 'blue'];
for (let color of colors) {
console.log(color);
}
함수 (Function)
함수는 선언문, 표현식, 화살표 함수로 정의할 수 있습니다. 화살표 함수는 자체 this와 arguments를 갖지 않습니다.
// 함수 선언문
function multiply(x, y) {
return x * y;
}
// 함수 표현식
const divide = function(x, y) {
return x / y;
};
// 화살표 함수 및 매개변수 활용
const processOrder = (price, discount = 0, ...options) => {
const finalPrice = price - (price * discount);
console.log('Options:', options); // 나머지 매개변수는 배열로 수집됨
return finalPrice;
};
processOrder(100, 0.1, 'giftWrap', 'express');
객체와 배열
객체 (Object)
const userProfile = {
username: 'dev_master',
level: 99,
isActive: true
};
// 속성 접근
console.log(userProfile.username);
console.log(userProfile['level']);
// 객체 순회 및 유틸리티
console.log(Object.keys(userProfile));
console.log(Object.values(userProfile));
console.log(Object.entries(userProfile));
배열 (Array)
const inventory = ['apple', 'banana', 'cherry'];
// 요소 추가 및 제거
inventory.push('date'); // 맨 뒤 추가
inventory.unshift('avocado'); // 맨 앞 추가
inventory.pop(); // 맨 뒤 제거
inventory.shift(); // 맨 앞 제거
// 배열 변형 및 탐색
const upperFruits = inventory.map(fruit => fruit.toUpperCase());
const hasBanana = inventory.some(fruit => fruit === 'banana');
const totalLength = inventory.reduce((acc, curr) => acc + curr.length, 0);
console.log(upperFruits);
console.log(hasBanana);
console.log(totalLength);
오류 처리 및 폼 유효성 검사
// 오류 처리
try {
const data = JSON.parse('invalid json');
} catch (error) {
console.error('파싱 오류 발생:', error.message);
} finally {
console.log('데이터 처리 프로세스 종료');
}
// 폼 유효성 검사
function validateRegistrationForm() {
const form = document.forms['registrationForm'];
const emailInput = form['userEmail'].value;
if (!emailInput || emailInput.trim() === '') {
alert('이메일을 입력해 주세요.');
return false;
}
return true;
}
객체지향 프로그래밍 (Class)
class Animal {
constructor(name, sound) {
this.name = name;
this.sound = sound;
}
speak() {
console.log(`${this.name} says ${this.sound}`);
}
static getKingdom() {
return 'Animalia';
}
}
class Dog extends Animal {
constructor(name) {
super(name, 'Woof');
}
fetch(item) {
console.log(`${this.name} fetches the ${item}`);
}
}
const myDog = new Dog('Buddy');
myDog.speak();
myDog.fetch('ball');
내장 객체 (Math, Date, String)
// Math
const randomNum = Math.floor(Math.random() * 100);
const maxVal = Math.max(10, 20, 30);
// Date
const now = new Date();
const currentYear = now.getFullYear();
const currentMonth = now.getMonth() + 1; // 0부터 시작
// String
const text = ' JavaScript Programming ';
const trimmed = text.trim();
const replaced = trimmed.replace('Programming', 'Development');
const parts = replaced.split(' ');
console.log(parts);
비동기 처리 (Async/Await & Promise)
// Promise 생성 및 체이닝
const fetchUserData = new Promise((resolve, reject) => {
setTimeout(() => {
const success = true;
if (success) resolve({ id: 1, name: 'Alice' });
else reject(new Error('Network Error'));
}, 1000);
});
fetchUserData
.then(user => console.log('User:', user.name))
.catch(err => console.error(err.message))
.finally(() => console.log('Request completed'));
// Async/Await
async function loadDashboard() {
try {
const response = await fetch('/api/data');
const result = await response.json();
console.log(result);
} catch (error) {
console.error('Failed to load dashboard:', error);
}
}
// Promise 정적 메서드
// Promise.all([promise1, promise2]) - 모두 성공 시 완료
// Promise.race([promise1, promise2]) - 가장 먼저 완료된 것 반환
DOM 조작 및 이벤트
요소 선택 및 조작
// 요소 선택
const mainTitle = document.getElementById('main-title');
const buttons = document.querySelectorAll('.action-btn');
// 콘텐츠 및 속성 변경
mainTitle.textContent = '새로운 타이틀';
mainTitle.innerHTML = '<em>강조된 타이틀</em>';
const link = document.querySelector('a');
link.setAttribute('href', 'https://example.com');
link.href = 'https://example.com';
// 스타일 및 클래스 조작
mainTitle.style.color = 'navy';
mainTitle.classList.add('highlight');
mainTitle.classList.toggle('active');
// 노드 생성 및 추가
const newItem = document.createElement('li');
newItem.textContent = '새로운 항목';
document.querySelector('ul').appendChild(newItem);
이벤트 리스너 및 타이머
const submitBtn = document.querySelector('#submit-btn');
// 이벤트 등록
submitBtn.addEventListener('click', (event) => {
event.preventDefault();
console.log('버튼이 클릭되었습니다.');
});
// 타이머 설정 및 해제
const timerId = setTimeout(() => {
console.log('3초 후 실행');
}, 3000);
// 타이머 취소
// clearTimeout(timerId);
const intervalId = setInterval(() => {
console.log('1초마다 실행');
}, 1000);
// 인터벌 취소
// clearInterval(intervalId);