JavaScript
- 기본 데이터 유형 (문자열, 숫자, 배열, 객체 등)
- 제어 구조 (if-else, 반복문 등)
- 함수, 클로저, 화살표 함수
- 클래스와 프로토타입을 이용한 객체지향 프로그래밍
- 비동기 프로그래밍 (프로미스, async/await)
JavaScript에서 기본 데이터 유형, 제어 구조, 함수, 클로저, 화살표 함수, 클래스와 프로토타입을 이용한 객체지향 프로그래밍, 비동기 프로그래밍에 대한 간단한 예제를 하나씩 제공해 드리겠습니다.
- 기본 데이터 유형 (문자열, 숫자, 배열, 객체 등):
// 문자열
let name = "John";
console.log("Hello, " + name); // 출력: Hello, John
// 숫자
let a = 5;
let b = 3;
let sum = a + b;
console.log(sum); // 출력: 8
// 배열
let fruits = ["apple", "banana", "orange"];
console.log(fruits[1]); // 출력: banana
// 객체
let person = { name: "John", age: 25 };
console.log(person.name); // 출력: John
- 제어 구조 (if-else, 반복문 등):
// if-else 문
let age = 20;
if (age >= 18) {
console.log("성인입니다.");
} else {
console.log("미성년자입니다.");
}
// 반복문 (for 문)
let fruits = ["apple", "banana", "orange"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// 반복문 (while 문)
let count = 0;
while (count < 5) {
console.log(count);
count++;
}
- 함수, 클로저, 화살표 함수:
// 함수
function greet(name) {
console.log("Hello, " + name);
}
greet("Alice"); // 출력: Hello, Alice
// 클로저
function outerFunction() {
let outerVar = "I'm from outer function";
function innerFunction() {
console.log(outerVar);
}
return innerFunction;
}
let closure = outerFunction();
closure(); // 출력: I'm from outer function
// 화살표 함수
let add = (a, b) => a + b;
console.log(add(3, 4)); // 출력: 7
- 클래스와 프로토타입을 이용한 객체지향 프로그래밍:
// 클래스
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
getArea() {
return this.width * this.height;
}
}
let rect = new Rectangle(3, 4);
console.log(rect.getArea()); // 출력: 12
// 프로토타입을 이용한 객체 생성
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function() {
console.log("Hello, my name is " + this.name);
};
let person = new Person("John", 25);
person.greet(); // 출력: Hello, my name is John
- 비동기 프로그래밍 (프로미스, async/await):
Copy// 프로미스
function asyncTask() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("
Task completed successfully!");
}, 2000);
});
}
asyncTask()
.then(result => console.log(result)) // 출력: Task completed successfully!
// async/await
async function doAsyncTask() {
try {
let result = await asyncTask();
console.log(result); // 출력: Task completed successfully!
} catch (error) {
console.log("An error occurred:", error);
}
}
doAsyncTask();