JS chapter03 데이터 실행하기
안녕하세요. 오늘은 JavaScript에서 다양한 데이터 실행 방법과 관련된 내용을 알려드리겠습니다.
1. 함수
선언적 함수
1
2
3
4
5
function greet() {
console.log("Hello!");
}
greet(); // "Hello!"
익명 함수
1
2
3
4
5
let greet = function() {
console.log("Hello!");
};
greet(); // "Hello!"
매개변수 함수
1
2
3
4
5
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet("John"); // "Hello, John!"
리턴값 함수
1
2
3
4
5
6
function add(a, b) {
return a + b;
}
let result = add(3, 5);
console.log(result); // 8
매개변수 + 리턴값 함수
1
2
3
4
5
6
function multiply(a, b) {
return a * b;
}
let result = multiply(4, 6);
console.log(result); // 24
화살표 함수 (Arrow Functions)
선언적 화살표 함수
1
2
3
4
5
const greet = () => {
console.log("Hello!");
};
greet(); // "Hello!"
익명 화살표 함수
1
2
3
const greet = () => console.log("Hello!");
greet(); // "Hello!"
매개변수 화살표 함수
1
2
3
const greet = name => console.log(`Hello, ${name}!`);
greet("Alice"); // "Hello, Alice!"
리턴값 화살표 함수
1
2
3
4
const add = (a, b) => a + b;
let result = add(3, 5);
console.log(result); // 8
매개변수 + 리턴값 화살표 함수
1
2
3
4
const multiply = (a, b) => a * b;
let result = multiply(4, 6);
console.log(result); // 24
2. 함수 유형
함수와 매개변수를 이용한 형태
1
2
3
4
5
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet("John"); // "Hello, John!"
함수와 변수를 이용한 형태
1
2
3
4
5
let greeting = function() {
console.log("Hello!");
};
greeting(); // "Hello!"
함수와 배열을 이용한 형태
1
2
3
4
5
function greet(names) {
names.forEach(name => console.log(`Hello, ${name}!`));
}
greet(["John", "Alice"]); // "Hello, John!" "Hello, Alice!"
함수와 객체를 이용한 형태
1
2
3
4
5
6
function greet(person) {
console.log(`Hello, ${person.name}! You are ${person.age} years old.`);
}
let person = { name: "John", age: 30 };
greet(person); // "Hello, John! You are 30 years old."
함수와 객체 및 배열을 이용한 형태
1
2
3
4
5
6
7
8
9
10
11
12
13
14
function greet(people) {
people.forEach(person => {
console.log(`Hello, ${person.name}! You are ${person.age} years old.`);
});
}
let people = [
{ name: "John", age: 30 },
{ name: "Alice", age: 25 }
];
greet(people);
// "Hello, John! You are 30 years old."
// "Hello, Alice! You are 25 years old."
객체 안에 함수를 이용한 형태
1
2
3
4
5
6
7
8
let person = {
name: "John",
greet: function() {
console.log(`Hello, my name is ${this.name}.`);
}
};
person.greet(); // "Hello, my name is John."
객체 생성자 함수
1
2
3
4
5
6
7
8
function Person(name, age) {
this.name = name;
this.age = age;
}
let john = new Person("John", 30);
console.log(john.name); // "John"
console.log(john.age); // 30
프로토타입 함수
1
2
3
4
5
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name}.`);
};
john.greet(); // "Hello, my name is John."
객체 리터럴 함수
1
2
3
4
5
6
7
8
let person = {
name: "John",
greet() {
console.log(`Hello, my name is ${this.name}.`);
}
};
person.greet(); // "Hello, my name is John."
3. 비동기 방식
즉시실행 함수
1
2
3
(function() {
console.log("Immediately invoked function expression (IIFE)");
})();
파라미터 함수
1
2
3
4
5
6
7
8
9
10
function fetchData(url, callback) {
fetch(url)
.then(response => response.json())
.then(data => callback(data))
.catch(error => console.error("Error fetching data:", error));
}
fetchData("https://api.example.com/data", function(data) {
console.log(data);
});
재귀 함수
1
2
3
4
5
6
7
8
function factorial(n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
console.log(factorial(5)); // 120
콜백 함수 (Callback Functions)
1
2
3
4
5
6
7
8
9
10
function fetchData(url, callback) {
fetch(url)
.then(response => response.json())
.then(data => callback(data))
.catch(error => console.error("Error fetching data:", error));
}
fetchData("https://api.example.com/data", function(data) {
console.log(data);
});
비동기 방식 : 프로미스 (Promises)
1
2
3
4
5
6
7
8
9
10
11
12
function fetchData(url) {
return new Promise((resolve, reject) => {
fetch(url)
.then(response => response.json())
.then(data => resolve(data))
.catch(error => reject(error));
});
}
fetchData("https://api.example.com/data")
.then(data => console.log(data))
.catch(error => console.error("Error fetching data:", error));
비동기 방식 : async/await
1
2
3
4
5
6
7
8
9
10
11
12
13
async function fetchData(url) {
try {
const response = await fetch(url);
const data = await response.json();
return data;
} catch (error) {
console.error("Error fetching data:", error);
}
}
fetchData("https://api.example.com/data")
.then(data => console.log(data))
.catch(error => console.error("Error fetching data:", error));
위의 예시들을 통해 JavaScript에서 다양한 데이터를 실행하고 활용하는 방법을 알아보았습니다. 함수의 다양한 유형과 비동기 처리 방식을 이해하면 JavaScript에서 보다 효율적인 코드를 작성할 수 있습니다.
This post is licensed under CC BY 4.0 by the author.