눈송이의 개발생활

[JavaScript]문법정리(1) - 데이터 타입, 연산 본문

Programming Languages/JavaScript

[JavaScript]문법정리(1) - 데이터 타입, 연산

꾸지새미언니

1. Data Types

📌 let

  • added in ES6
  • 유일한 변수 선언 명령어
  • Muttable (read&write)
//global scope
let name = 'suah';
console.log(name);
{
    //block scope
    let age = 23;
    console.log(age);
}
  • block scope : {} 블록 밖에서는 블록 안으로 접근할 수 없음
  • global scope : 전역 변수. application 시작부터 끝까지 메모리에 탑재되어있기 때문에 최대한 덜 쓰는 것이 좋음

📌 var

  • 지금은 잘 사용하지 않는 변수 선언 명령어
  • 선언하기 전에 값을 할당할 수 있음
  • var hoising : 어디에 변수를 선언했느냐에 상관없이 항상 제일 위로 선언을 끌어 올려주는 것
console.log(age);        //undefined
age =4;
console.log(age);        //4
var age; 

📌 const

  • 값을 변경할 수 없음
  • Immutable (read only)

    항상 immutable data types를 선호해야하는 이유 :

    1. security (보안)
    2. thread safety - 여러 쓰레드에서 동시에 값을 변경할 수 있기 때문에
    3. reduce human mistakes (인간의 욕심은 끝이없고 같은 실수를 반복하지!)

2. Variable Types

  • primitive (single items) → number, string, boolean, null, undefined, symbol
  • object, box container
  • function, first-class function

📌 Integer

다 number로 통일

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

console.log(`value: ${count}, type: ${typeof count}`);
//value: 17, type: number

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

special numeric values

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

📌 String

아래의 3가지 console.log는 다 같은 문자열을 출력한다

value: hello suah, type: String 
const char = 'c';
const suah = 'suah';
const greeting = 'hello ' + suah;

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

const helloSuah = `hello ${suah}!`; 
console.log(`value: ${helloSuah}, type: ${typeof helloSuah}`);

console.log('value: ' + helloSuah + ' type: ' + typeof helloSuah);

+ 기호는 문자열들을 연결시켜준다
${변수} 문자열인 변수를 출력한다


📌 Boolean

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

    • null : let nothing = null; (직접 지정해서 null로 값이 할당되어 있음)
    • undefined : let X (값이 할당되어 있지 않음)
  • true : 다른 모든 값들


📌 Symbol

  • Map 또는 다른 자료구조에서 고유 식별자가 필요하거나, 동시에 다발적으로 일어날 수 있는 코드에서 우선순위를 주고싶을 때 사용
  • 정말 고유한 식별자가 필요할 때 사용
//symbol : creates unique identifiers for objects 
const symbol1 = Symbol('id');
const symbol2 = Symbol('id');
console.log(symbol1 === symbol2)    //false

//symbol똑같이 만들고 싶을 때 
const gSymbol1 = Symbol.for('id');
const gSymbol2 = Symbol.for('id');
console.log(gSymbol1 === gSymbol2)    //true

//string으로 출력하고 싶을 때 
console.log(`value : ${symbol1.description}`)

🔍 Dynamic Typing

javascript는 type을 계속 변경할 수 있는 언어

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

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

text = '7' + 5;
console.log(`value: ${text}, type: ${typeof text}`);
//value: 75, type: string 
//5를 string으로 인식해서 문자 '7' 뒤에 문자 '5'를 붙여줌

text = '8' / '2';
console.log(`value: ${text}, type: ${typeof text}`);
//value: 4, type: number 
//나누기 연산자가 있어서 compiler가 숫자를 나눠야한다고 생각함
let text = 'hello';
console.log(text.charAt(0));   //h

text = '8' / '2';
console.log(text.charAt(0));   //runtime error
//string이 아니라 number이기 때문에 error 발생 

💡 NOTE
Immutable data types : primitive types, frozen objects (i.e. object.freeze())
Mutable data types: 모든 객체는 default로 mutable이다. (in JS)


3. Operators

📌 string

console.log('my' + 'cat');   //my cat 
console.log('1' + 2);   //12
console.log(`string literals: 1 + 2 = ${1 + 2}`);   //string literals: 1 + 2 = 3
console.log("ellie\'s book")   //ellie's book

+ string 2개 이상 연결할 때 사용
" ` string 내에서 사용하고 싶을 때 \를 기호 앞에 써주기


📌 numeric

  • + addition
  • - subtraction
  • / division
  • % remainder (나머지)
  • * multiplication
  • ** exponentiation (제곱)

📌 increment and decrement

let counter = 2;
const preIncrement = ++counter;
//counter = counter + 1
//preIncrement = counter
console.log(`preIncrement: ${preIncrement}, counter: ${counter}`);   
//preIncrement: 3, counter: 3

const postIncrement = counter++;
// postIncrement = counter;
// counter = counter + 1;
console.log(`postIncrement: ${postIncrement}, counter: ${counter}`);   
//postIncrement: 3, counter: 4

const preDecrement = --counter;
console.log(`preDecrement: ${preDecrement}, counter: ${counter}`);   
//preDecrement: 3, counter: 3

const postDecrement = counter--;
console.log(`postDecrement: ${postDecrement}, counter: ${counter}`);   
//postDecrement: 3, counter: 2

📌 assignment and comparison

  • += -= *= /=
  • < <= > >=

📌 logical

  • || (or) : 처음으로 true 나오면 검사 멈춘다. 하나라도 true면 멈춤

    • expression이나 함수를 뒤에 배치하는 것이 효율적이다
  • &&(and) : 처음으로 false 나오면 멈춘다. 하나라도 false면 멈춤

    • heavy operator 뒤로 보내는 것이 효과적! 효율적!
const value1 = true;
const value2 = 4 < 2;   //false

console.log(`or: ${value1 || value2 || check()}`);
// value1이 true이기 때문에 check()함수는 실행되지 않음  

console.log(`and: ${value1 && value2 && check()}`);

// often used to compress long if-statement
// nullableObject && nullableObject.something

function check() {
  for (let i = 0; i < 10; i++) {
    //wasting time
    console.log('😱');
  }
  return true;
}

// ! (not)
console.log(!value1);

📌 Equality

  • == loose equality : type 변경해서 확인함
  • === stric equality : type 다르면 같지 않음. strict equality 사용하는 것이 더 좋고 안정적
const stringFive = '5';
const numberFive = 5;

console.log(stringFive == numberFive);   //true
console.log(stringFive != numberFive);   //false

console.log(stringFive === numberFive);   //false
console.log(stringFive !== numberFive);   //true

// object equality by reference
const suah1 = { name: 'suah' };
const suah2 = { name: 'suah' };
const suah3 = suah1;

console.log(suah1 == suah2);   //false
console.log(suah1 === suah2);   //false
console.log(suah1 === suah3);   //true
// equality - puzzler
console.log(0 == false);   //true
console.log(0 === false);   //false (다른 type)
console.log('' == false);   //true
console.log('' === false);   //false (다른 type)
console.log(null == undefined);   //true
console.log(null === undefined);   //false (다른 type) 

참고 : 드림코딩by엘리 - 자바스크립트 기초

Comments