variable

heyj·2022년 1월 24일
0

HTML/CSS/Javascript

목록 보기
2/8
post-thumbnail

Variable

1. 'use strict'

added in ES5, use this for vanilla Javasctipt

2. variable

- let (added in ES6)

// only use let if variables needs to change
// multiple data type

let name = 'john';
console.log(name); // john

name = 'angela';
console.log(name); // angela

- const

// use const whenever possible
// favor immutable data type always for a few reason - because of these: security, thread safety, reduce human mistakes...
const favorite = 'rock music';
console.log(favorite) // rock music

- var를 쓰지 않는 이유?

// 변수를 선언도 하기 전에 값을 할당할 수 있고, 
심지어 로그에 값은 출력되지 않지만 변수가 선언된 것을 확인할 수 있다.

console.log(gender); // female
gender = female;
var gender;

// block scope을 무시

3. variable type

- primitive, single item: number, string, boolean, null, undefined, symbol

  • object, box container
  • function, first-class function
  • Immutable data type: primitive types, frozen object(i,e. Object.freeze())
  • mutable data type : all objects by default are mutable in JS

- number - special numeric values : infinity, -infinity, NaN, bigInt

const count = 17; // integer
const size = 18.3; // decimal number

console.log(`value: ${count}, type: ${typeof count}`);
console.log(`value: ${size}, type: ${typeof size}`);
const infinity = 1 / 0
const negativeInfinity = -1 / 0
const NaN = 'not a number' / 2;

console.log(infinity) // Infinity
console.log(negativeInfinity) // -Infinity
console.log(NaN) // NaN


// bigInt
const bigInt = 12446814518405912380n;
console.log(`value: ${bigInt}, type: ${typeof bigInt}`)

- string

const hello = 'hello'
const name = 'john'
const greeting = hello + name

console.log(`value: ${greeting}, type: ${typeof greeting}`) //value: hellojohn, type: string

// templete literals
const hi = `hello, ${name}`
console.log(`value: ${hi}, type: ${typeof hi}`) // value: hello, john, type: string

- boolean

// false: 0, null, undefined, NaN, ''
// true: any other value

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

- null

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

- undefined

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

- symbol(create unique identifiers for objects)

- object

const john = { name: 'john', age: 30 }

Dynamic typing

  • 선언할 때 어떤 타입인지 선언하지 않고 런타임에 할당된 값에 따라서 타입이 변경될 수 있다. -> TypeScript가 나온 배경

0개의 댓글