Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
307 changes: 307 additions & 0 deletions hyunmin/ZeroBase/입문자 자바스크립트/01. JS-데이터.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,307 @@
> 제로베이스 자바스크립트 기초개념 JS 데이터 부분 정리
> 축약된 부분이 존재할 수 있습니다.

# 원시형 데이터

### 문자 데이터

JS에서 문자 데이터를 만드는 방법은 세 가지가 존재한다.

> " ", ' ', \` \`

백틱 같은 경우에는 문자 데이터 중간에 변수를 보간할 수 있다.

```js
const s1 = "황현민";
const s2 = "18살";

// 템플릿 리터럴
// 이런식으로 중간에 값을 넣는 것을 데이터 보간이라고
const s3 = `안녕하세요! 제 이름은 ${s1}이고 나이는 ${s2}입니다.`;
```

### 숫자 데이터

JS에서 숫자 데이터는 정수 및 부동소수점 숫자를 나타낸다.

```JS
const n1 = 123
const n2 = 123.1233

// 만약 산술연산을 다른 데이터와 하게 된다면?
const n3 = 123 + "안녕" // 문자 데이터를 우선해서 문자 데이터가 된다.
const n4 = 123 + undefined // NaN (숫자가 아닌 숫자)가 나온다.
```

### 불린(boolean) 데이터

boolean은 true와 false를 가지는 참/거짓 논리 데이터이다.

```js
const a = true;
const b = false;
```

### null 데이터

null 데이터는 존재하지 않는(noting), 비어 있는(empty), 알 수 없는(unknown) 값을 명시적으로 나타낸다.

```JS
let age = null
```

### undefined 데이터

undefined 데이터는 값이 할당되지 않은 상태를 나타낼 때 사용한다.
변수는 선언했지만, 값을 할당하지 않았다면 해당 변수에 undefined가 암시적으로 사용된다.

```js
let age;
console.log(age);
```

# 참조형 데이터

### 배열 데이터

배열(array) 데이터는 순서가 있는 여러 데이터의 집합이다.
배열에 포함 각 데이터는 아이템(Item)혹은 요소(Element)라고 부른다.

```js
const f = ["사과", "수박", "메론"];
const n = [123, 456, 789];

// 배열으 길이 확인
console.log(f.length); // 3
console.log(n.length); // 5

// 배열의 아이템 번호(index)로 아이템을 확인 (indexing)
// 숫자는 0부터 시작한다. (Zero-Base-Numbering)
console.log(f[2]); // 메론
console.log(n[1]); // 456

// 배열의 모든 아이템을 순회하고 싶다?
for (let i = 0; i < f.length; i += 1) {
console.log(f[i]);
}
for (let i = 0; i < n.length; i += 1) {
console.log(n[i]);
}
```

### 객체 데이터

객체(object) 데이터는 순서가 없는 Key(키)와 Value(값)의 쌍으로 어우러진 데이터 집합이다.
객체에 포함된 각 데이터를 속성(Property)라고 부르고,
만약 그 데이터가 함수인 경우에는, 메소드(method)라고 부른다.

```js
const user = {
name: "현민",
age: 18,
isValid: true,
email: "gyejeongjin@gmail.com",
hello: function () {
return `내 이름은 ${this.name}이다. 내 나이는 ${this.age}`;
},
};

// 점 표기법(Dot Notation)을 사용해, 객체의 속성이나 메소드에 접근할 수 있다.
console.log(user.name);
console.log(user.age);
console.log(user.isValid);
console.log(user.email);
console.log(user.hello());

// 대괄호 표기법(Bracket Notation)을 사용해, 객체의 속성이나 메소드에 접근할 수 있다.
console.log(user["name"]);
console.log(user["age"]);
console.log(user["isValid"]);
console.log(user["email"]);
console.log(user["hello"]());

// 대괄호 표기법은 좀 더 동적으로 사용 할 수 있다.
const key = "name";
console.log(user[key]);
```

### 함수 데이터

함수(Function) 데이터, 어떤 작업을 수행하기 위해 필요한 여러 코드의 집합으로, 코드를 추상화하고 재사용성을 확보한다.
이 함수를 자바스크립트에서는 하나의 데이터 종류로 취급한다.

```js
// 함수 선언문(Declaration)
function add(a, b) {
// console.log(a);
// console.log(b);
return a + b;
}

console.log(add);
console.log(add(1, 2));
console.log(add(31, 14));
console.log(add(5, 8));

// 함수 표현식
const sub = function (a, b) {
return a - b;
};

console.log(sub);
console.log(sub(2, 1));
console.log(sub(14, 10));
console.log(sub(8, 5));
```

# 변수

변수(Variable)란, 데이터(값)의 이름을 지정한 것이다.
이름이 있으면, 그 이름으로 언제든지 데이터를 재사용 할 수 있다.

```js
// const 키워드는 상수(Constant)를 의미하며, 한 번 선언하면 다른 값으로 변경 할 수 없다.
const c = 12;
console.log(c);
console.log(c);
// c = 34; // Error: Assignment to constant variable.
// JS는 Error가 발생하면 아래 코드를 싹다 무시한다.

// let 키워드는 선언한 값을 다른 값으로 바꿀 수 있다.
let l = 12;
console.log(l);
console.log(l);
l = 13;
console.log(l);
console.log(l);
```

일단 기본적으로 const를 사용하고 값을 바꿔야 한다면 let으로 바꿔서 사용하면 된다.

# 형 변환

형 변환(Type Convension)이란, 데이터가 상황에 따라 적절한 데이터 타입(자료형)으로 변환되는 것을 말한다.

```js
const a = 1;
const b = "1";

// == 동등 연산자
console.log("동등", a == b); // true
// === 일치 연산자
cnsole.log("일치", a === b); // false

// 다음 코드는 모두 true를 출력합니다.
console.log("=================");
console.log(123 == "123");
console.log(1 == true);
console.log(0 == false);
console.log(null == undefined);
console.log("" == false);
// 동등연산자는 비교하는 개념에서는 명확하지 않아 쓰는걸 권장하지 않는다.

// 다음 코드는 모두 false 출력합니다.
console.log("=================");
console.log(123 === "123");
console.log(1 === true);
console.log(0 === false);
console.log(null === undefined);
console.log("" === false);
```

# 참(Truthy)과 거짓(Falsy)

```js
// '참'으로 평가되는 값 (Truthy)
if (true) {
console.log("참!");
}
if ({}) {
console.log("참!");
}
if ([]) {
console.log("참!");
}
if (42) {
console.log("참!");
}
if ("0") {
console.log("참!");
}
if ("false") {
console.log("참!");
}
if (new Date()) {
console.log("참!");
}
if (-42) {
console.log("참!");
}
if (12n) {
console.log("참!");
}
if (3.14) {
console.log("참!");
}
if (-3.14) {
console.log("참!");
}
if (Infinity) {
console.log("참!");
}
if (-Infinity) {
console.log("참!");
}
// ...

// '거짓'으로 평가되는 값 (Falsy)
if (false) {
console.log("거짓..");
}
if (null) {
console.log("거짓..");
}
if (undefined) {
console.log("거짓..");
}
if (42) {
console.log("거짓..");
}
if (0) {
console.log("거짓..");
}
if (-0) {
console.log("거짓..");
}
if (NaN) {
console.log("거짓..");
}
if (0n) {
console.log("거짓..");
}
if ("") {
console.log("거짓..");
}
// ...
```

참인 값은 너무 많기 때문에, 거짓인 값만 외워주면 된다.

# 데이터 타입 확인

지금까지 배운 데이터 타입을 코드상에서 확인하는 방법 알아보기

```JS
const data = {
  string: "123",
  number: 123,
  boolean: true,
  null: null,
  undefined: undefined,
  array: [1, 2, 3],
  object: { a: 1, b: 2, c: 3 },
  function: function () {},
};
```

이런 객체가 존재할 때, 어떤식으로 데이터 타입을 확인할 수 있을지 알아보자.
Loading