본문 바로가기
Front-end/Web

[JS] data types, let vs var, hoisting

by 안녕주 2021. 8. 26.

Variable

변수는 변경될 수 있는 값을 뜻한다. 읽고쓰기가 가능

[variable.js]

//1. User strict
//added in ES 5
//use this for Valina JavaSCript
'use strict';


// 2. Variable, rw(read/write)
//let (added in ES6)

let name = 'hellozo0';
console.log(name);
name = 'hi';
console.log(name);

 

Block Scope

1. Block scope : 블록 밖에서 블록 안에 있는 것들에 접근할 수 없음

2. Global scope : 어디서나 접근이 가능함, 어플리케이션이 실행되면서 끝날때까지 항상 메모리에 있기에 최소한으로 써야한다.

[variable.js]

//1. User strict
//added in ES 5
//use this for Valina JavaSCript
'use strict';


// 2. Variable, rw(read/write)
//let (added in ES6)
let globalName = 'global name';

{
let name = 'hellozo0';
console.log(name);
name = 'hi';
console.log(name);
console.log(globalName);
} 

console.log(name); //값 출력 안된다.
console.log(globalName);

 

var,  hoisting

1. var 는 요즘 쓰지 않는다.

2. var hoisting = 어디에서 선언되었는지에 관계없이 항상 제일 위로 선언을 끌어올려주는 것을 말한다.

3. var는 block scope이 없다, block scope을 무시한다.

// var(don't ever use this!)
// var hoisting (move declaration from bottom to top)
// var는 no block scope
console.log(age); //출력됨
age = 4;
console.log(age); //출력됨
var age;

{ 
    age = 4;
    var age;
}
console.log(age); //출력됨

 

Constant

값을 한번 할당하면 절대 바뀌지 않는 변수. 읽기만 가능

// 3. Constant, r(read only)
// use const whenever possible.
// only use let if variable needs to change.
const daysInWeek = 7;
const maxNumber = 5;

 

Variable types

1. Primitive type : 더이상 작은 단위로 나눠질 수 없는 한가지의 아이템  

    - number, string, boolean, null, undefined, symbol

    - value로 값이 저장됨

2. Object type : 싱글 아이템들을 여러개로 묶어서 한 박스로 관리하는것

    - object를 가르키는 reference가 값에 저장됨

3. function : 변수로서 할당이 가능, 리턴 가능

// 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 data type always for a few reasons:
//  - security
//  - thread safety
//  - reduce human mistakes

 

[number]

자바스크립트에서는 number 하나면 숫자를 사용할 수 있다.

- number이라도 선언하지 않고 사용할 수 있다.

- infinity, -infinity, NaN

- bigInt

//4. Variable types
// primitive, single item : number, string, boolean, null, undefined, symbol
// object, box container
// function, first-class function
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 - specla 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)
const bigInt = 1234567890123456789012345678901234567890n; //over (-2**53) ~ (2**53)
console.log(`value: ${bigInt}, type: ${typeof bigInt}`);
Number.MAX_SAFE_INTEGER;

 

[string]

한글자든, 여러글자든 다 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}`);
console.log('value: ' + helloBob + ' type: ' + typeof helloBob);

 

[boolean]

false와 true

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

- true 

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

 

[null, defined]

1. null : null을 할당하는 것은 null(아무값도 아님)로 값을 지정

2. defined : 선언은 되었지만 값이 하나도 지정되어 있지 않음

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

// undefined
let x;
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);
const gSymbol1 = Symbol.for('id');
const gSymbol2 = Symbol.for('id');
console.log(gSymbol1 === gSymbol2); // true
console.log(`value: ${symbol1.description}, type: ${typeof symbol1}`);

여기까지가 primitive type

--

[object]

// object, real-life object, data structure
const ellie = { name: 'ellie', age: 20 };
ellie.age = 21;

 

Dynamic typing

변수가 동적으로 변경

// 5. Dynamic typing: dynamically typed language
let text = 'hello';
console.log(text.charAt(0)); //h
console.log(`value: ${text}, type: ${typeof text}`);
text = 1;
console.log(`value: ${text}, type: ${typeof text}`);
text = '7' + 5;
console.log(`value: ${text}, type: ${typeof text}`);
text = '8' / '2';
console.log(`value: ${text}, type: ${typeof text}`);
console.log(text.charAt(0)); //에러

 


Thanks for 드림코딩

https://youtu.be/OCCpGh4ujb8

댓글