JavaScript는 웹 브라우저에서 실행되는 프로그래밍 언어로, 동적이고 인터랙티브한 웹 페이지를 만들 수 있게 해줍니다.
JavaScript는 웹 개발을 위한 고급 프로그래밍 언어입니다. 원래는 웹 브라우저에서만 실행되었지만, 현재는 서버 사이드(Node.js)에서도 사용되며, 모바일 앱과 데스크톱 애플리케이션 개발에도 활용됩니다.
1. 동적 타입 언어 - 변수의 타입이 런타임에 결정됩니다. - 유연한 프로그래밍이 가능합니다.
2. 이벤트 기반 프로그래밍 - 사용자 상호작용에 반응하는 이벤트 핸들러를 지원합니다. - 비동기 프로그래밍이 자연스럽습니다.
3. 객체 지향 프로그래밍 - 프로토타입 기반 상속을 지원합니다. - ES6부터 클래스 문법도 지원합니다.
변수 선언:
// var (구식, 사용 권장하지 않음) var oldWay = "구식 방법"; // let (블록 스코프) let modernWay = "현대적 방법"; // const (상수) const constantValue = "변하지 않는 값";
함수 정의:
// 함수 선언 function traditionalFunction() { return "전통적인 함수"; } // 함수 표현식 const arrowFunction = () => { return "화살표 함수"; }; // 즉시 실행 함수 (function() { console.log("즉시 실행"); })();
객체와 배열:
// 객체 const person = { name: "홍길동", age: 30, greet() { return `안녕하세요, ${this.name}입니다.`; } }; // 배열 const numbers = [1, 2, 3, 4, 5]; const doubled = numbers.map(n => n * 2);
요소 선택:
// ID로 선택 const element = document.getElementById('myId'); // 클래스로 선택 const elements = document.getElementsByClassName('myClass'); // CSS 선택자로 선택 const element = document.querySelector('.myClass'); const elements = document.querySelectorAll('.myClass');
이벤트 처리:
// 이벤트 리스너 추가 element.addEventListener('click', function(event) { console.log('클릭됨!'); }); // 화살표 함수 사용 element.addEventListener('mouseover', (event) => { element.style.backgroundColor = 'red'; });
DOM 조작:
// 요소 생성 const newElement = document.createElement('div'); newElement.textContent = '새로운 요소'; // 요소 추가 document.body.appendChild(newElement); // 요소 제거 element.remove(); // 속성 설정 element.setAttribute('class', 'newClass');
콜백 함수:
// 비동기 작업 예제 setTimeout(() => { console.log('3초 후 실행'); }, 3000); // AJAX 요청 fetch('/api/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error));
Promise:
const myPromise = new Promise((resolve, reject) => { // 비동기 작업 setTimeout(() => { const success = Math.random() > 0.5; if (success) { resolve('성공!'); } else { reject('실패!'); } }, 1000); }); myPromise .then(result => console.log(result)) .catch(error => console.error(error));
async/await:
async function fetchData() { try { const response = await fetch('/api/data'); const data = await response.json(); return data; } catch (error) { console.error('데이터 가져오기 실패:', error); } } // 사용 fetchData().then(data => console.log(data));
ES6 모듈:
// math.js export const add = (a, b) => a + b; export const subtract = (a, b) => a - b; export default class Calculator { multiply(a, b) { return a * b; } } // main.js import Calculator, { add, subtract } from './math.js'; console.log(add(5, 3)); // 8 console.log(subtract(10, 4)); // 6 const calc = new Calculator(); console.log(calc.multiply(6, 7)); // 42
CommonJS (Node.js):
// math.js module.exports = { add: (a, b) => a + b, subtract: (a, b) => a - b }; // main.js const math = require('./math.js'); console.log(math.add(5, 3)); // 8
구조 분해 할당:
// 배열 구조 분해 const [first, second, ...rest] = [1, 2, 3, 4, 5]; // 객체 구조 분해 const { name, age, ...otherProps } = person;
템플릿 리터럴:
const name = "홍길동"; const greeting = `안녕하세요, ${name}님!`; const multiLine = ` 여러 줄의 텍스트를 쉽게 작성할 수 있습니다. `;
클래스:
class Animal { constructor(name) { this.name = name; } speak() { return `${this.name}이(가) 소리를 냅니다.`; } } class Dog extends Animal { speak() { return `${this.name}이(가) 멍멍 짖습니다.`; } } const dog = new Dog('바둑이'); console.log(dog.speak()); // "바둑이가 멍멍 짖습니다."
콘솔 메서드:
console.log('일반 로그'); console.error('에러 메시지'); console.warn('경고 메시지'); console.info('정보 메시지'); // 객체 출력 console.table([ { name: '홍길동', age: 30 }, { name: '김철수', age: 25 } ]); // 성능 측정 console.time('작업 시간'); // ... 작업 수행 console.timeEnd('작업 시간'); </code> **브레이크포인트:** <code javascript function debugFunction() { debugger; // 브라우저에서 실행 시 여기서 멈춤 console.log('디버깅 중...'); }
— 이 페이지는 자동으로 생성되었습니다.