Javascript

J·2025년 5월 22일

Arrow Function () => ...

with {} or without {}

// ✅ correct: without {}
queryFn: () => axios.get("/api/users").then(res => res.data)

// ✅ correct: without {} ---- use need `return`
queryFn: () => {
  return axios.get("/api/users").then(res => res.data)
}

// ❌ wrong: without {} nor `return` ---- `return` is mandatory
queryFn: () => {
  axios.get("/api/users").then(res => res.data)
}

자주 겪는 에러

⨯ SyntaxError: Expected ',' or '}' after property value in JSON at position 29 (line 3 column 5)

요청에 json body를 넣었는데 ,로 key value pair를 구분하지 않았을 때 발생한다.

window

웹브라우저에 접근할 수 있게 해주는 객체이다. 여러 데이터, 메소드를 가지고 있다.

window.alert("alertMessage")
window.console.log("hello world")

// 편의상 window는 생략 가능
alert("alertMessage")
console.log("hello world")

자주 쓰이는 window의 객체 및 메소드

window.console.log("something")
window.alert("something")
window.prompt("something") // return submitted string
window.confirm("something") // true if clicked yes, false otherwise

숫자 조작

Math.trunc vs Math.floor

실수 = 정수부분 + 소수부분 (단, 소수부분은 [0, 1)의 수)
floor: 소수부분을 없앰
trunc: 소숫점 아래가 안 보이는 수를 반환

// examples
console.log(Math.floor(-1.3)) // prints -2, b/c -1.3 = -2 + 0.7
console.log(Math.trunc(-1.3)) // prints -1, hides decimal

parseInt

parseInt은 소숫점 나오기 전까지만 읽어들이는 것이다.
trunc처럼 소숫점 아래를 지우는 것이다. 정수부분을 반환하는 게 아니다.
정수 부분을 반환하려면 parseFloat(something) -> Math.floor(parsedFloat)를 써야 한다.

// examples
// -1.3 = -2 + 0.7
console.log(parseInt("-1.3")) // prints -1
consoel.log(Math.floor(parseFloat("-1.3"))) // prints -2

논리 연산자 && ||

논리 연산자는 조건을 판단한 마지막 값을 반환한다.

// && examples

// && 조건은 양쪽이 참일 때 만족된다.
// 1. 왼쪽이 참 -> 오른쪽도 확인해야
// 2. 오른쪽 확인, 마지막으로 판단한 오른쪽 return
console.log(true && false) // prints false
console.log("123" && null) // prints null

// 1. 왼쪽이 거짓 -> 조건 불만족하므로 종료, 마지막으로 판단한 왼쪽 return
console.log(false && true) // prints false (left one)
console.log(null && "123") // prints null

// || examples
// || 조건은 한쪽이라도 참일 때 만족된다.
// 1. 왼쪽이 참, 조건 만족, 마지막으로 판단한 왼쪽 return
console.log(true || false) // prints true
console.log("123" || null) // prints 123

// 1. 왼쪽이 거짓 -> 오른쪽 확인해야
// 2. 오른쪽 확인, 마지막으로 판단한 오른쪽 return
console.log(false || true) // prints true
console.log(false || false) // prints false (left one)
console.log(null || 0) // prints 0

reduce

Array에서만 사용 가능

기본 구조

const array1 = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (accumulator, currentValue) => accumulator + currentValue,
  initialValue,
);

console.log(sumWithInitial);
// Expected output: 10

MDN Array.prototype.reduce()

HTML manipulation

style manipulation

자바스크립트에서 접근 가능한 요소의 스타일은 인라인 스타일로 한정된다.

const element = document.getElementById("someId")
element.style = "" // 인라인 스타일 초기화
// class, id, 상속을 통해 받은 스타일은 유지

fetch

원래 뜻: go get something and bring it back

0개의 댓글