JS/[드림코딩] 엘리 (완)

03강. 데이터타입, data types, let vs var, hoisting

web_seul 2020. 7. 1. 01:42
반응형

1. Use strict

added in ES 5

use this for Vanila Javascript.

'use strict';

 

2. Variable, rw(read/write)

 let (added in ES6)

let globalName = 'global name';

{
  let name = 'ellie';
  console.log(name);

  name = 'hello';
  console.log(name);

  console.log(globalName);
}

console.log(name); //->{ } 내부에서 정의된 변수는 외부에서 찾을 수 없음
console.log(globalName); //어디서든 가능

 

 var (don't ever use this!)

- var hoisting: (move declaration from bottom to top) 위치에 상관없이 변수를 최상단으로 끌어올림

console.log(age);	//undefined
age=4;

console.log(age);	//4
var age;      		// 스크립트 중앙에 정의해도 가장 위에 정의한 효과


비교)
name = 4;
let name;			//Error

- has no block scope

{
  age =4;
  var age;
}
console.log(age); //{ } 내부에 선언된 변수가 밖에서도 출력됨 -> 큰 프로젝트에서 문제됨

 

 

3. Invariable, r(read only)

 Constant 

use const whenever possible.

only use 'let' if variable needs to change.

const daysInWeek =7;

const maxNumber =5;

 

 Note! 

Immutable data types: primitive types, frozen objects(i.e object.freeze())

Mutable data types: all objects by default are mutable in JS

favor immutable type always for a few reasons:

1) security_ 코드변경방지

2) thread safety_ 효율적인 thread 유지

3) reduce human mistakes




4. Variable types

 primitive , single item_ 더이상 나뉘지않는 가장작은단위 item

: number, string, boolean, null, undefind,symbol

 object , box container_single 묶음

 function , first-class function_ 변수 할당가능, parameter인자로 전달 가능, function return 가능

 

cf)

C data types for number_세세하게 메모리 할당관리가능

int main(){
    short a = 12;	//2bytes
    int a = 12;		//4bytes
    long b = 1234;	//8bytes
    float d = 1.2f;	//4bytes
    double e = 8.2;	//16bytes
   
    return = 0;
}

 

JAVA data types for number

class Main{
    public static void main(String[] args){
        byte a = 12;
        short b = 12;
        long c = 12;
        int d =12;
        float e = 1.2f;
        double f = 1.2;
    }
 }

 

JS_only number

let a = 12;
let b = 1.2;
const count = 17; //integer
console.log(`value: ${count}, type: ${typeof count}`);

const size = 17.1; //decimal number
console.log(`value: ${size}, type: ${typeof size}`);

 

TS date types for number

let a: number = 12;
let b: number = 1.2;

 

 number _ special numeric values: infinity, -infinity, Nan

const infinity = 1/0;
const negativeInfinity = -1/0;
const nAn = 'not a number'/2;

console.log(infinity);
console.log(negativeInfinity);
console.log(nAn);

 bigInt  (fairly new, don't use it yet)_ 숫자범위제한(-2**53~2*53)이 있는 js에서 n을 붙이면 숫자로 인식 (only chrome, firefox)

const bigInt = 123456789123456789n;

console.log(`value: ${bigInt}, type: $(typeof bigInt}`);

Number.MAX_SFAE_INTEGER;

 string 

const char = 'c';

const brendan = 'brendan';

const greeting = 'hello' + brendan;

console.log(`value: ${greeing}, type: ${typeof greeting}`);

const helloBob = `hi ${brendan}!`; //template literals(string)

console.log(`value: ${helloBob}, type: ${typeof helloBob}`);

` 을 안쓴 기존스타일
console.log('value:' + helloBob + 'type:' + typeof helloBob);

 boolean 

false:0, null, undefined, NaN, ' '

true: any other value

const canRead = true;
console.log(`value:${canRead}, type: ${typeof canRead}`);

const test = 3<1;	//false;
console.log(`value: ${test}, type: ${typeof test}`);

 null _값을 가지지않았다고 정의됨

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

 undefined _정의자체가 되지않음

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

 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}, type: ${typeof symbol1}`); //error
console.log(`value: ${symbol1.description}, type: ${typeof symbol1}`); //true
				└ string으로 변환

 object , real-life object, data structure

const ellie = {name:'ellie', age:20};
ellie.age = 21;	//const 내부의 memory변경

 

5. Dynamic typing: dynamically typed language_ 프로그램이 동작할때 할당된 값에 따라 type이 설정, 변경

let text ='hello';
console.log(text.charAt(0));  //h
console.log(`value: ${text}, type: ${typeof text}`); //string

text = 1;
console.log(`value: ${text}, type: ${typeof text}`); //number

text ='7'+5;
console.log(`value: ${text}, type: ${typeof text}`); //75_string

text ='8'/'2';
console.log(`value: ${text}, type: ${typeof text}`); //4_number

console.log(text.charAt(0)); //error_중간에 string으로 바뀜(error가 많이 발생하는 경우)

 

TS_ JS위에 type이 더 올려진 언어, BABEL 사용

 

반응형