JavaScript는 웹 페이지의 동적인 기능을 구현하기 위한 프로그래밍 언어로, 주로 클라이언트 측에서 실행. HTML 및 CSS로 구성된 정적인 웹 페이지를 동적으로 변경하고 상호 작용할 수 있게 해준다.
// 주석은 이렇게 작성합니다.
// 변수 선언과 할당
var x = 5;
let y = 10;
const pi = 3.14;
// 조건문
if (x > y) {
console.log('x는 y보다 큽니다.');
} else if (x < y) {
console.log('x는 y보다 작습니다.');
} else {
console.log('x와 y는 같습니다.');
}
// 반복문
for (let i = 0; i < 5; i++) {
console.log('반복 횟수:', i);
}
// 함수 정의
function add(a, b) {
return a + b;
}
// 함수 호출
let result = add(3, 4);
console.log('덧셈 결과:', result);
var: ES5 이전에 사용되던 변수 선언 키워드. 함수 스코프를 가지며 호이스팅이 발생.let: 블록 스코프를 가지는 변수 선언 키워드. 변수의 재할당 가능.const: 블록 스코프를 가지는 상수 선언 키워드. 한 번 할당된 값은 변경할 수 없다.if, else if, else: 조건에 따라 코드 블록을 실행.let num = 10;
if (num > 0) {
console.log('양수입니다.');
} else if (num < 0) {
console.log('음수입니다.');
} else {
console.log('0입니다.');
}
for, while, do-while: 코드 블록을 반복해서 실행.// for 문
for (let i = 0; i < 5; i++) {
console.log(i);
}
// while 문
let j = 0;
while (j < 5) {
console.log(j);
j++;
}
// do-while 문
let k = 0;
do {
console.log(k);
k++;
} while (k < 5);
// 함수 선언
function multiply(a, b) {
return a * b;
}
// 함수 표현식
const divide = function(a, b) {
return a / b;
};
// Arrow 함수
const add = (a, b) => a + b;
// 함수 호출
console.log(multiply(3, 4));
console.log(divide(6, 2));
console.log(add(1, 2));
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Event Handling</title>
</head>
<body>
<button id="myButton">Click me</button>
<script>
// 버튼 요소 가져오기
const button = document.getElementById('myButton');
// 이벤트 핸들러 등록
button.addEventListener('click', function() {
alert('버튼이 클릭되었습니다.');
});
</script>
</body>
</html>
// 객체
const person = {
name: 'John',
age: 30,
job: 'Developer'
};
// 배열
const fruits = ['apple', 'banana', 'orange'];
console.log(person.name); // John
console.log(fruits[1]); // banana
// Fetch API를 이용한 데이터 가져오기
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
// DOM을 통한 요소 선택
const myElement = document.getElementById('myElement');
// 요소의 내용 변경
myElement.innerHTML = '새로운 내용';
// 새로운 요소 생성 및 추가
const newElement = document.createElement('p');
newElement.textContent = '새로운 단락';
document.body.appendChild(newElement);
// 비동기적인 데이터 가져오기 예제 (Promise)
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('데이터가 성공적으로 가져왔습니다.');
}, 2000);
});
}
fetchData()
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
function outerFunction() {
let outerVariable = '외부 변수';
function innerFunction() {
console.log(outerVariable);
}
return innerFunction;
}
const closureFunction = outerFunction();
closureFunction(); // 외부 변수
// 화살표 함수
const add = (a, b) => a + b;
// 클래스
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`안녕하세요, ${this.name}(${this.age}세)입니다.`);
}
}
const john = new Person('John', 30);
john.greet();