JavaScript

내장 객체 (Built-in Objects)

1. 내장 객체란?

내장 객체(Built-in Object)는 자바스크립트가 미리 만들어 제공하는 객체다. 우리가 따로 정의하지 않아도 어디서든 바로 쓸 수 있으며, 숫자 계산·날짜 처리·데이터 변환 등 자주 필요한 기능을 담고 있다.

flowchart TD
    A["내장 객체"] --> B["값 다루기<br/>Number · String · Boolean"]
    A --> C["자료구조<br/>Array · Object"]
    A --> D["유틸리티<br/>Math · Date · JSON"]
    A --> E["전역 함수<br/>parseInt · isNaN …"]
    style A fill:#ede7f6,stroke:#5e35b1
    style D fill:#e8f5e9,stroke:#43a047

이미 다룬 내장 객체

String의 문자열 메서드는 연산자 & 문자열 & 제어문에서, Array의 배열 메서드와 Object는 객체 & 배열 & ES6 문법에서 다뤘다. 이 단원에서는 아직 다루지 않은 Number, Math, Date, JSON, 전역 함수를 살펴본다.


2. Number

Number는 숫자를 다루는 내장 객체다. 값을 숫자로 변환하거나, 자릿수를 다듬는 메서드를 제공한다.

Number() — 숫자로 변환

값을 숫자 타입으로 변환한다. 숫자로 바꿀 수 없으면 NaN을 반환한다.

console.log(Number("10"));      // 10
console.log(Number("  10  "));  // 10   (앞뒤 공백은 무시)
console.log(Number("10.33"));   // 10.33
console.log(Number(true));      // 1
console.log(Number("John"));    // NaN  (변환 불가)
console.log(Number("10,33"));   // NaN  (쉼표는 숫자가 아님)

10 10 10.33 1 NaN NaN

숫자를 다듬는 메서드

메서드

설명

예시 → 결과

toFixed(n)

소수점 n자리로 반올림한 문자열

(3.14159).toFixed(2) → "3.14"

toString()

숫자를 문자열로 변환

(255).toString() → "255"

toString(진법)

진법 변환

(255).toString(16) → "ff"

toLocaleString()

지역 형식(천 단위 쉼표 등)

(1234567).toLocaleString() → "1,234,567"

let price = 1234567;
let pi = 3.14159;

console.log(pi.toFixed(2));            // "3.14"
console.log(price.toLocaleString());   // "1,234,567"
console.log((255).toString(16));       // "ff" (16진수)

3.14 1,234,567 ff


3. Math

Math는 수학 계산을 위한 객체다. 인스턴스를 만들지 않고 Math.메서드() 형태로 바로 쓴다.

자주 쓰는 메서드

메서드

설명

예시 → 결과

Math.round(x)

반올림

Math.round(4.5) → 5

Math.ceil(x)

올림

Math.ceil(4.1) → 5

Math.floor(x)

내림

Math.floor(4.9) → 4

Math.abs(x)

절댓값

Math.abs(-7) → 7

Math.max(...)

최댓값

Math.max(1, 5, 3) → 5

Math.min(...)

최솟값

Math.min(1, 5, 3) → 1

Math.pow(x, y)

거듭제곱

Math.pow(2, 10) → 1024

Math.sqrt(x)

제곱근

Math.sqrt(16) → 4

Math.random()

0 이상 1 미만 난수

0.7263…

console.log(Math.round(4.5));        // 5
console.log(Math.floor(4.9));        // 4
console.log(Math.max(1, 5, 3));      // 5
console.log(Math.sqrt(16));          // 4
console.log(Math.PI);                // 3.141592653589793

5 4 5 4 3.141592653589793

실전: 난수 만들기

Math.random()은 0 이상 1 미만의 실수를 반환한다. 이를 응용해 원하는 범위의 정수를 뽑는다.

// 1 ~ 6 사이의 정수 (주사위)
let dice = Math.floor(Math.random() * 6) + 1;
console.log(dice);   // 예: 4

// min ~ max 사이 정수를 뽑는 함수
function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomInt(1, 100));   // 예: 57

4. Date

Date는 날짜와 시간을 다루는 객체다. new Date()로 인스턴스를 만든다.

let now = new Date();              // 현재 날짜·시간
let birthday = new Date("2026-03-31");   // 특정 날짜
let custom = new Date(2026, 2, 31);      // 월은 0부터! (2 = 3월)

월(month)은 0부터 시작한다

Date에서 월은 0(1월)부터 11(12월)까지다. new Date(2026, 2, 31)은 3월 31일이다. 가장 자주 하는 실수이니 주의한다.

날짜 정보 꺼내기

메서드

반환

getFullYear()

연도 (4자리)

getMonth()

월 (0~11)

getDate()

일 (1~31)

getDay()

요일 (0=일 ~ 6=토)

getHours() / getMinutes() / getSeconds()

시 / 분 / 초

let d = new Date("2026-05-25T10:30:00");

console.log(d.getFullYear());   // 2026
console.log(d.getMonth() + 1);  // 5  (0부터이므로 +1)
console.log(d.getDate());       // 25
console.log(d.getHours());      // 10

2026 5 25 10

// 오늘 날짜를 "YYYY-MM-DD"로 포맷
let today = new Date();
let y = today.getFullYear();
let m = String(today.getMonth() + 1).padStart(2, "0");
let day = String(today.getDate()).padStart(2, "0");
console.log(`${y}-${m}-${day}`);   // 예: 2026-05-25

5. JSON

JSON (JavaScript Object Notation)

JSON은 데이터를 주고받기 위한 텍스트 형식이다. 자바스크립트 객체와 모양이 비슷해 다루기 쉽고, 텍스트라 전송 속도가 빠르다. 서버와 데이터를 주고받을 때(예: fetch) 사실상의 표준으로 쓰인다.

JSON 객체는 객체↔문자열 변환을 위한 두 메서드를 제공한다.

  • JSON.stringify(값): 자바스크립트 값 → JSON 문자열 (데이터를 보낼 때)

  • JSON.parse(문자열): JSON 문자열 → 자바스크립트 값 (데이터를 받을 때)

flowchart LR
    A["JS 객체<br/>{ book: 책, price: 123 }"] -->|JSON.stringify| B["JSON 문자열<br/>#quot;{ book: 책 , price: 123 }#quot;"]
    B -->|JSON.parse| A
    style A fill:#e8f5e9,stroke:#43a047
    style B fill:#e3f2fd,stroke:#1e88e5
// 객체 → JSON 문자열
let book = { title: "책", price: 12000 };
let jsonStr = JSON.stringify(book);
console.log(jsonStr);           // '{"title":"책","price":12000}'
console.log(typeof jsonStr);    // "string"

// JSON 문자열 → 객체
let parsed = JSON.parse(jsonStr);
console.log(parsed.title);      // "책"
console.log(typeof parsed);     // "object"

{"title":"책","price":12000} string 책 object

JSON.parse는 try...catch로 감싸기

잘못된 형식의 문자열을 JSON.parse하면 오류가 발생한다. 외부에서 받은 데이터를 파싱할 때는 try...catch로 감싸 안전하게 처리한다.

try {
  let data = JSON.parse(input);
} catch (e) {
  console.error("JSON 파싱 에러");
}

6. 전역 함수 (Global Functions)

어떤 객체에도 속하지 않고 어디서나 바로 호출할 수 있는 함수들이다. 값을 변환하거나 검사할 때 자주 쓴다.

함수

설명

parseInt(값)

문자열을 정수로 변환

parseFloat(값)

문자열을 실수로 변환

isNaN(값)

숫자가 아니면 true

isFinite(값)

유한한 숫자이면 true

console.log(parseInt("42px"));      // 42   (숫자 부분만 추출)
console.log(parseFloat("3.14rem")); // 3.14
console.log(parseInt("abc"));       // NaN
console.log(isNaN("hello"));        // true  (숫자가 아님)
console.log(isNaN("123"));          // false (숫자로 볼 수 있음)

42 3.14 NaN true false

Number() vs parseInt()

  • Number("42px") → NaN (전체가 숫자여야 함)

  • parseInt("42px") → 42 (앞쪽 숫자만 읽음)

CSS 값("20px")처럼 단위가 붙은 문자열에서 숫자를 뽑을 때는 parseInt/parseFloat가 유용하다.

마지막 수정 2026년 10월 22일