자바스크립트 문법
JavaScript 언어 자체의 기능
JavaScript 엔진(V8, SpiderMonkey 등)**에서 제공하는 기능으로 어디서든 동작 가능 (브라우저, Node.js, 서버 등)
JavaScript Keyword
In Operator(javascript property in object) : The in operator returns true if the specified property is found in the specified object or its prototype chain. Its syntax is:
변수선언
- let : 변경 가능한 변수
- const : 변경 불가능한 상수
- var : 옛날 방식 (요즘은 잘 안 씀)
클래스 정의
클래스 내에 method와 attribute를 모두 정의해줌
class Person {
constructor(name) {
this.name = name; // 여기서 속성 초기화
}
sayHello() {
console.log("Hello " + this.name);
}
}
const p = new Person("Alice");
p.sayHello(); // Hello Alice
attribute는 나중에 동적으로 추가가능
const p = new Person("Alice");
p.age = 30; // constructor 없이 나중에 동적으로 속성 추가
console.log(p.age); // 30
String Object Method
Stringinstance.toUpperCase() : 문자열을 대문자로 변환 후 반환함
Stringinstance.length() : 문자열의 길이를 반환함
Stringinstance.IndexOf() : 문자의 index를 찾아서 반환하며, 찾지 못하면 -1를 반환함.
Stringinstance.trim() : whitespace를 제거함
출력
- console.log("Hello, World!"); // 문자열 출력
- console.log({ name: "Alice", age: 25 }); // 객체 출력
String
- + conCatenation : "hello"+"world" = "helloworld"
- stringInstance.length() : 글자의 길이를 출력
변수 생성
- var : ES6 이전 방식, 현재는 잘 사용하지 않음 (함수스코프)
- let : var보다 안전하며 최신 코드에서 사용 (블록스코프)
- const : 변경할 필요 없는 값에 사용 (블록스코프)
Math 객체사용
- Math.random() : 0.0 이상 1.0 미만의 실수를 반환
- Math.floor() : 소수점 제거
- Math.floor(Math.random() * 10) : 0부터 9까지 정수
함수 프로그래밍
- Arrow Function : a shorter way to write a function.
Full Function Definition
function sayHi() {
console.log("Hi");
}
short Function Definition without inputParameter
const sayHi = () => {
console.log("Hi");
};
Callback Functions
- A callback is a function that is passed as an argument to another function and is called later
- Basic and direct
setTimeout(() => {
console.log("Callback after 1 second");
}, 1000);
- Gets messy when you nest too many:
doSomething(() => {
doAnother(() => {
doMore(() => {
// callback hell 😵
});
});
});
Asynchronous Handling in JavaScript
Why Asynchronous? : In the context of web browsers, there are many tasks like loading images, downloading files, or fetching data from a server. These tasks can take time to complete and you wouldn't want your browser to freeze or stop responding while these tasks are being done. browser is designed to work within the constraints of a single-threaded execution mode
Promises
- 비동기 연산의 “미래의 값”을 표현하기 위한 표준 객체 (표현 방식) 입니다
- 상태와 값을 가진 컨테이너
Promise 의 특징
내부 상태(state)를 가진다
- Promise 는 3가지 상태를 가집니다. 이 상태는 한 번 정해지면 바뀌지 않아요. 즉 fulfilled 혹은 rejected 으로 결정되면(lock-in) 그 상태로 고정됩니다. pending → fulfilled/rejected 로 상태가 바뀌면서 .then()이나 .catch()가 실행되는 것 입니다
값(value)을 담는 객체
- 지금은 값이 없거나 준비되지 않았을 수도 있음.
- resolve() 혹은 reject() 가 호출되면 Promise 객체의 내부 상태(state)가 pending → fulfilled 혹은 rejected 로 한번만 바뀌며 해당 값을 “가짐” 상태가 됨. 하지만 여전히 그 객체는 Promise 타입이다.
- 결과 값(value) 이 들어 있느냐 (fulfilled)
- 에러(reason) 가 들어 있느냐 (rejected)
- 아직 아무 것도 없느냐 (pending)의 차이만 있는 것.
- Promise 정의
- executor 이란 그냥 Promise를 만들 때 넘기는 콜백 함수로 두 개의 함수 argument (resolve, reject)를 받도록 설계
new Promise(executor)
executor(resolve, reject)
const promise = new Promise((resolve, reject) => {
// 여기서 비동기 작업 수행
if (성공) {
resolve(value); // 상태를 fulfilled로 바꾸고 value 저장
} else {
reject(error); // 상태를 rejected로 바꾸고 error 저장
}
});
- then() : 실행된 Promise의 결과를 후처리하기 위한 함수.
- promise.then(onFulfilled, onRejected)
- onFulfilled : Promise 가 fulfilled (성공) 상태가 되면 호출되는 함수. Promise 의 결과 값을 인자로 받음.
- onRejected(선택적) : Promise 가 rejected (실패) 상태가 되면 호출되는 함수. 에러 객체를 인자로 받음.
- Return 값: .then() 은 새로운 Promise 객체를 반환. 그래서 .then().then() 으로 체이닝 가능
- 에러 처리 : .catch() 를 체인에 붙여서 에러를 한 번에 처리 가능. promise.then(...).catch(...)
- promise.then(onFulfilled, onRejected)
async/await
await 은 Promise가 “resolve 될 때까지 기다렸다가, 그 값을 꺼내오는 문법이야.**
- Promise 가 fulfilled 상태가 될 때까지 현재 async 함수의 흐름을 멈추고(suspend)
- 완료되면 resolve된 값을 받아서 다음 코드로 이어가.
- ✅ Looks like synchronous code but runs asynchronously
- ✅ Easier to try/catch for error handling
- 🔥 Best choice for clean readable async code
async function run() {
const result = await new Promise(resolve => setTimeout(() => resolve("Done"), 1000));
console.log(result);
}
run();