728x90
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" consent="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="variable.js"></script>
</head>
<body></body>
</html>
1. 변수(Variable)
변경될 수 있는 값
//엄격모드 : 안전한 코딩을 위한 하나의 가이드라인
//use strict를 입력하지 않으면 변수 선언 없이도 변수를 사용하거나 할 수 있으므로 그것을 방지하기 위함
'use strict';
//let (ES6에 추가됨) : 변수를 선언할 때 사용
let name = 'ellie';
console.log(name);
name = 'hello';
console.log(name);
2. Block scope
코드를 블럭안에 작성하는것 / 블럭안에 작성한 코드는 블럭 밖에서 사용할 수 없음
//엄격모드 : 안전한 코딩을 위한 하나의 가이드라인
//use strict를 입력하지 않으면 변수 선언 없이도 변수를 사용하거나 할 수 있으므로 그것을 방지하기 위함
'use strict';
//global변수 : 어느 곳에서나 접근이 가능 / 어플리케이션이 실행되는 순간부터 끝날때까지 메모리에 탑재되어 있기 때문에 최소한으로 사용하는것이 좋음
let globalName = 'globalName';
{
let name = 'ellie';
console.log(name);
name = 'hello';
console.log(name);
console.log(globalName);
}
console.log(name); //블럭안에서 선언한 변수이기 때문에 블럭 밖에서는 사용이 불가능 (값이 출력되지 않음)
console.log(globalName);
3. 변수 선언 방식
1) var : 변수 재선언 가능 / 변수 재할당 가능
var를 사용하지 않는 이유:
- 블럭을 무시함 (블럭안에 선언한 변수를 어디에서나 사용할 수 있음)
- 값을 선언하기도 전에 쓸 수 있음 (var hoisting)
hoisting : 어디에 선언하든 선언을 제일 위로 끌어 올려 주는 것
2) let (Mutable 데이터 타입 - 값의 변경이 가능) : 변수 재선언 불가능 / 변수 재할당 가능
3) constant (Immutable 데이터 타입 - 한번 설정하면 값이 절대로 바뀌지 않음) : 변수 재선언 불가능 / 변수 재할당 불가능
Immutable 데이터 타입의 장점
- 한번 작성한 값을 변경할 수 없기 때문에 보안에 좋음
- 실수를 줄일 수 있음
4. Variable types
primitive(더이상 작은 단위로 나누어질 수 없는), single item (한가지 아이템) : number, string, boolean, null, undefiedn, symbol
object(싱글 아이템들을 여러개 묶어서 한 단위로, 한 박스로 관리할 수 있도록 해줌), box container
function(자바 스크립트에서는 function도 데이터 타입 중 하나), first-class function(function도 다른 데이터 타입처럼 변수에 할당이 가능하며, 함수의 파라미터, 리턴 타입으로도 전달이 가능)
1) Number
자바 스크립트에서는 number타입만 이용하여 숫자를 선언하면 됨.
let a = 12;
let b = 1.2;
데이터 타입을 선언하지 않아도 다이나믹하게 타입이 결정되기 때문에 어떤 숫자든 할당 해주면됨.
const count = 17; //integer
const size = 17.1; //decimal number
console.log(`value: ${count}, type: ${typeof count}`); // ${count} 변수값 자체를 그대로 출력
console.log(`value: ${size}, type: ${typeof size}`);
//number
const infinity = 1/0;
const negativeInginity = -1/0;
const nAn = 'not a number' / 2; //숫자가 아닌 string을 숫자로 나누면 NaN
console.log(infinity);
console.log(negativeInginity);
console.log(nAn);
2) String
//string
const char = 'c';
const brendan = 'brendan';
const greeting = 'hello' + brendan;
console.log(`value: ${greeting}, type: ${greeting}`);
const helloBob = `hi ${brendan}!`;
console.log(`value: ${helloBob}, type: ${typeof helloBob}`); //아래의 코드와 같은 의미 ``을 사용하면 좀더 간단하게 표현 가능
console.log('value: ' + helloBob + 'type: ' + typeof helloBob);
3) boolean
false : 0, null, undefined, NaN, ' '(비어져있는 string)
true : 다른 값들
//boolean
const canRead = true;
const test = 3<1; //false
console.log(`value: ${canRead}, type: ${typeof canRead}`);
console.log(`value: ${test}, type: ${typeof test}`);
4)null
텅텅 비어있는 값이라고 지정해주는것
//null
let noting = null;
console.log(`value: ${noting}, type: ${typeof noting}`);
5)undefined
선언은 되었지만 아무 값이 지정되지 않은 경우(텅텅 비어있는지 값이 들어가있는지 정해지지 않은 상태)
//undefined
let x;
//let x = undefined; 라고 해주어도됨
console.log(`value: ${x}, type: ${typeof x}`);
6) symbol
우선순위를 주고 싶을 때 고유한 식별자를 주는 것
//symbol
const symbol1 = Symbol('id');
const symbol2 = Symbol('id');
console.log(symbol1 == symbol2); //다르다고 출력됨, 동일한 string을 작성해도 다른 symbol로 인식
//동일한 string을 사용하여 동일한 symbol을 만들고 싶은 경우
const gSymbol1 = Symbol.for('id'); //주어진 string에 맞는 symbol을 만듦
const gSymbol2 = Symbol.for('id');
console.log(gSymbol1 == gSymbol2);
console.log(`value: ${symbol1.description}, type: ${typeof symbol1}`); //symbol은 .description을 사용하여 Stirng우로 변환 후 출력해야함
7) object
일상생활에서 보는 물건과 물체들을 대표할 수 있는 박스 형태
//object
const ellie = {name: 'ellie', age: 20};
ellie.age = 21;
8) typeof 명령
변수에 저장 되어 있는 데이터의 타입을 알아봄
var num = 10;
console.log(typeof num); //number
5. Dynamic typing
//선언할 때 어떤 타입인지 선언하지 않아도 런타임시에 할당된 값에 따라 타입이 변경 될 수 있음
//Dynamic typing
let text = 'hello'; //string
console.log(text.charAt(0)); //h
console.log(`value: ${text}, type: ${typeof text}`);
text = 1; //number
console.log(`value: ${text}, type: ${typeof text}`);
text = '7' + 5; //string
console.log(`value: ${text}, type: ${typeof text}`);
text = '8' / '2'; //number
console.log(`value: ${text}, type: ${typeof text}`);
//console.log(text.charAt(0)); //오류발생 number타입이기 때문에
더보기
정리
1. Immutable data types : 데이터타입 절대 변경 불가능 / premitive types, frozen objesct
2. Mutable data types : 대부분의 모든 오브젝트
728x90
'프로그래밍 언어 > Javascript' 카테고리의 다른 글
오브젝트? (0) | 2021.08.23 |
---|---|
클래스와 오브젝트의 차이점(class vs object), 객체지향 언어 클래스 정리 (0) | 2021.08.20 |
Arrow Function은 무엇인가? 함수의 선언과 표현 (0) | 2021.08.20 |
operator, if, for loop (0) | 2021.08.19 |
Visual Studio Code 추천 익스텐션 (0) | 2021.08.19 |