일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
- fragment
- 스프링부트
- Javscript
- scrollview
- TextView
- GoogleMaps
- npm
- 자바스크립트
- stylesheet
- Kotlin
- RecyclerView
- Hook
- Linux
- 리액트
- 랜덤넘버
- TypeScript
- Android
- Java
- React
- array
- SpringBoot
- button
- JavaScript
- JS
- 랜덤번호
- nodejs
- 코틀린
- 구글맵스
- 오버라이딩
- 안드로이드
- Today
- Total
타닥타닥 개발자의 일상
JavaScript 기초 - 변수와 데이터 타입 : let / const / number / string/ boolean / null / undefine / symbol 본문
JavaScript 기초 - 변수와 데이터 타입 : let / const / number / string/ boolean / null / undefine / symbol
NomadHaven 2022. 8. 11. 23:21시작하기 전 설정
1. index.html 파일 생성
프로젝트 폴더에 자바스크립트 코드파일(variable.js) 외에도
브라우저의 콘솔창을 통해 결과를 출력하게 해주는 index.html 파일도 생성한다.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="variable.js"></script>
</head>
<body>
</body>
</html>
2. Use srtict 입력하기
바닐라 자바스크립트 개발시 제일 먼저 'use strict'를 선언해주는 게 좋다.
자바 스크립트의 변수
Variable
1. let
ES6에 추가된 변수로, ES6는 글로벌하게 개발자들이 이용하는 자바스크립트 문법이다.
이전에는 var라는 변수를 썼지만, var에는 치명적인 단점이 있다.
바로 var는 hoisting의 성격을 가지고 있기 때문이다.
hoisting :move declaration from bottom to top 어디에 선언했냐에 상관 없이 항상 선언을 끌어올려주는 것
만약 아래 순서와 같이 코드가 작성되어 있다 해도
'use strict';
console.log(age); // undefined로 출력
{
age=4;
var age;
}
console.log(age); //4로 출력
let globalName = 'global name';
{
let name = 'nomad';
console.log(name);
name='haven';
console.log(name);
console.log(globalName)
}
console.log(name); // 블록안에 있는 변수는 외부에서 출력하지 못한다.
console.log(globalName); // 블록 안에서 변수 쓰지 않고 바로 정의하는 변수를
//global scope이라고 부른다. 블록 안에서도, 밖에서도 출력 가능하다.
globalName과 같은 글로벌한 변수들은 어플리케이션이 실행되는 순간부터 끝날때까지 메모리에 탑재되기 때문에 최소한으로 쓸 필요가 있다.
let은 메모리에 값을 읽고 쓰는게 가능하다.
let 변수에 ellie라고 할당한 다음 hello라고 변경하는게 가능하다.
2. Const
선언한 뒤에 변경할수 없는 immutable한 변수.
웬만하면 값을 할당한 다음 변경되지 않는 데이터 값에 사용해야하는 변수이다.
읽기만 가능하다. 그래서 변수를 할당한 뒤에는 다른 값으로 변경하는 게 불가능 하다.
변수의 값이 바뀌어야될 좋은 이유가 없다면 웬만해선 Const를 사용하는 편이 좋다.
const daysInWeek = 7;
const maxNumber = 5;
변수의 종류들
Variables Types
const count = 17; //Integer
const size = 17.1; //Decimal number
console.log(`value: ${count}, type: ${typeof count}`);
console.log(`value: ${size}, type: ${typeof size}`);
Imuuntable data type: primitive types, frozen objects (i.e. object.freeze())
Mutable data type: all object by default are mutable in JS
primitive type 같은 경우는 변수가 바로 메모리에 저장된다.
variable은 value가 메모리에 저장된다.
반대로 object는 너무 커서 메모리에 한번에 올라갈수 없다.
const ellie라고 선언한다음 object를 할당하게 되면 ellie가 가르키는 곳엔 ref가 있다.
ref는 실제로 object가 담겨있는 메모리를 가르킨다.
ellie가 가르키고 있는 포인터만 잠겨서 ellie가 다른 object로 변경이 불가능 하지만,
ellie의 나이와 이름은 변경이 가능하다.
object는 obejct를 가리키는 ref가 메모리에 저장된닫.
📌number에 속하지만 특수한 값을 가지는 경우 : infinity, -infiniry, Nan(Not a Number)
const infinity = 1/0; //수를 0으로 나누면 무한대가 된다
const negativeInfinity = -1/0; //음수를 0으로 나누면 음의 무한대가 된다.
const nAn = 'not a number'/2;
console.log(infinity);
console.log(negativeInfinity);
console.log(nAn);
*연산시 유효한 값을 받지 못하게 되면 숫자가 아닌 Infinity, -Infinity가 뜨는 경우가 있으니 주의
📌bigInt : 새로 추가된 변수로 많이 쓰지는 않지만, 큰 숫자를 표현할때 사용한다.
const bigInt= 15648465456484655132184121238412123n;
console.log(`value: ${bigInt}, type: ${typeof bigInt}`);
📌string 문자열
const char = 'c';
const brendan = 'brendan';
const greeting ='hello' + brendan;
const helloBob = `hi ${brendan}!`; // template literals (string)
console.log(`value: ${greeting}, type: ${typeof greeting}`);
console.log(`value: ${helloBob}, type: ${typeof helloBob}`);
📌 boolean
false: 0, null, undefined, Nan, ''(비어진 string)
true: any other value
const canRead = true;
const test = 3<1; // fasle
console.log(`value: ${canRead}, type: ${typeof canRead}`);
console.log(`value: ${test}, type: ${typeof test}`);
📌 null 텅 비어 있는 값
let nothing = null;
console.log(`value: ${nothing}, type: ${typeof nothing}`);
📌undefined 텅 비어있는 것과 값이 들어가 있는 것마저 정해지지 않은 값
let x;
console.log(`value: ${x}, type: ${typeof x}`);
📌symbol : map이나 자료구조에서 고유한 식별자가 필요할때, 동시에 다발적으로 일어날수 있는 코드에서 우선순위를 주고싶을 때 사용 create unique identifiers for objects map
const symbol1 = Symbol('id');
const symbol2 = Symbol('id');
console.log(symbol1===symbol2); //콘솔에 출력하면 false 나온다.
const gSymbol1 = Symbol.for('id');
const gSymbol2 = Symbol.for('id');
console.log(gSymbol1===gSymbol2); // true
console.log(`value: ${symbol1.description}, type: ${typeof symbol1}`);
*symbol은 바로 출력하면 error가 나므로 .description을 통해 출력해야 한다.
📌object 구조체. 실제의 사물, 데이터 구조등을 표현할때 쓰인다.
const haven = { name: 'haven', age: 20};
'코딩 기록 > JavaScript' 카테고리의 다른 글
배열을 받고 형식을 갖춘 문자로 출력하기 javascript JS (0) | 2022.12.06 |
---|---|
자바스크립트 함수/배열 이용해서 배열에 원하는 값 저장하기 array (0) | 2022.11.16 |
자바 스크립트 if 조건문으로 함수 만들어서 원하는 결과 출력하기 (0) | 2022.11.16 |
오픈 소스 pagination 이용하여 웹페이지 페이징하기 / 페이지 나누기 / javascript (0) | 2022.02.25 |
CGV 웹사이트 크롤링해서 HighChart 이용한 예매율 순위표 만들기 / j soup 이용 (0) | 2022.02.25 |