본문 바로가기
리뷰/javascript

자바스크립트 강의노트 #3 - 데이터타입, data types, let vs var, hoisting

by D마트 2022. 9. 9.
반응형

아래 내용은 위 강의 내용을 토대로 작성한 개인 공부용 학습 자료입니다.

기본적으로 강의 내용을 주로 요약하였지만, 일부 내용은 강의 내용과 다를 수 있습니다.

 

 

프로그래밍에서 중요한 것들

- 입력, 연산, 출력

- 데이터 전송

- CPU에 최적화된 연산

- 메모리의 사용을 최소화

 

 

Strict mode

- Vanilla JavaScript를 사용할 때는 'use strict'를 가장 상단에 선언해주는 것을 권장

// 1. Use strict
// added in ES 5
// use this for Vanilla JavaScript.
'use strict';

 

- (참고) Vanilla JavaScript

 

Vanilla JS - 나무위키

실제로는 바닐라에 대한 명확한 개념이 없고 의미가 혼용되는 경우가 많기 때문에 아래의 여러 오해를 사기도 한다. 바닐라 js는 (새로 나온) 프레임워크가 아니다.여러 기사나 글에서 바닐라 js

namu.wiki

 

외부 라이브러리나 프레임워크를 쓰지 않는 순수 JavaScript를 이르는 말이다. 사용자 정의된 라이브러리나 프레임워크 자체를 쓰지 않기 때문에 당연히 다른 라이브러리나 프레임워크를 사용했을 때보다 빠르고 호환성이 좋을 수밖에 없다. 또한 숙련된 사람일 수록 별의별 기능을 구현할 수 있다는 특징이 있다.

 

- (참고) Strict mode

 

Strict mode - JavaScript | MDN

Callout: 가끔 엄격하지 않은 기본값을 " 느슨한 모드(sloppy mode)"라고 부르기도 합니다. 공식적인 용어는 아니지만 혹시 모르니 알아두세요.

developer.mozilla.org

1. 기존에는 조용히 무시되던 에러들을 throwing합니다.
2. JavaScript 엔진의 최적화 작업을 어렵게 만드는 실수들을 바로잡습니다. 가끔씩 엄격 모드의 코드는 비-엄격 모드의 동일한 코드보다 더 빨리 작동하도록 만들어집니다.
3. 엄격 모드는 ECMAScript의 차기 버전들에서 정의 될 문법을 금지합니다.

 

 

Variable

- EC 6에 추가된 let 명령으로 변수를 선언할 수 있음

- Global scope 에서 선언된 전역변수는 어디서나 접근할 수 있음

let name = "kevin";

 

- Block scope 안에 변수를 선언하면, Block scope 바깥에서는 이 변수에 접근할 수 없음

{
    let name = 'kevin';
}

 

- Global scopeBlock scope에서 정의된 변수를 아래와 같이 출력하여 위 내용을 확인할 수 있음

// 2. Variable
// let (added in ES 6)

// 전역변수
let globalName = 'global name';

// Block scope
// Block 안에 정의된 변수는 Block 밖에서 사용할 수 없음
// 전역변수는 Block 안에서도 사용할 수 있음
{
    let name = 'kevin';
    console.log(name);
    name = 'hello';
    console.log(name);
    console.log(globalName);
}

console.log(name);
console.log(globalName);

 

- var는 이제 사용하지 않는 변수 선언 명령어로 Hoisting 문제(변수 선언을 가장 맨 위로 올려주는 문제)가 있음

// var (don't ever use this!)
// var hoisting (move delaration from bottom to top)
console.log(age); // undefined
age = 4;
console.log(age); // 4
var age; // Hoising

// var는 blcok scope이 없음
{
    age = 5;
    var age; // Hoisting
}
console.log(age); // 5

 

 

Constants

- 선언함과 동시에 값을 할당한 뒤로는 값을 변경할 수 없음 (Immutable data type)

- favor immutable data type always for a few reasons

  - security

  - thread safety

  - reduce human mistakes

// 3. Constants
const daysInWeek = 7;
const maxNumber = 5;
console.log(daysInWeek);
console.log(maxNumber);

 

 

Data types

Number

// Number 숫자형
const count = 17; // integer
const size = 17.1; // decimal number
console.log(`value: ${count}, type: ${typeof count}`);
console.log(`value: ${size}, type: ${typeof size}`);

// Number의 특별한 값 유형
const infinity = 1 / 0;
const negativeInfinity = -1 / 0;
const nAn = 'not a number' / 2;
console.log(`value: ${infinity}, type: ${typeof infinity}`)
console.log(`value: ${negativeInfinity}, type: ${typeof negativeInfinity}`)
console.log(`value: ${nAn}, type: ${typeof nAn}`)

 

Bigint

// 새로 추가된 Bigint 숫자형
// (fairly new, don't use it yet)
// over (-2**53 ~ 2**53)
const bigInt = 6789678967896789678967896789678967896789n;
console.log(`value: ${bigInt}, type: ${typeof bigInt}`)

 

String

// String 문자열
const char = "C";
const brendan = "brendan";
const greeting = "hello " + brendan;
console.log(`value: ${greeting}, type: ${typeof greeting}`);
const helloBob = `hi ${brendan}!`; // template literals (string)
console.log(`value: ${helloBob}, type: ${typeof helloBob}`);

 

Boolean

// Boolean
// false: 0, null, undefined, NaN, ''
// true: any other value
const canRead = true;
const text = 3 < 1; // false
console.log(`value: ${canRead}, type: ${typeof canRead}`);
console.log(`value: ${text}, type: ${typeof text}`);

// null
let nothing = null;
console.log(`value: ${nothing}, type: ${typeof nothing}`);


// undefined
let x; // or let x=undefined;
console.log(`value: ${x}, type: ${typeof x}`);
 

Symbol

// symbol, create unique identifiers for objects
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.description}`);
 
Object
// object, real-life object, data structure
const kevin = { name: "kevin", age: 30};
kevin.age = 15;
console.log(kevin);

 

Dynamic typing

// 5. Dynamic typing: dynamically typed language
let test = "hello";
console.log(test.charAt(0));
console.log(`value: ${test}, type: ${typeof test}`); // string
test = 1;
console.log(`value: ${test}, type: ${typeof test}`); // number
test = '7' + 5;
console.log(`value: ${test}, type: ${typeof test}`); // string
test = "8" / "2";
console.log(`value: ${test}, type: ${typeof test}`); // number
console.log(test.charAt(0)); // error
반응형