9/8 TIL

최준호·2022년 9월 8일
0

< 목차 >

  1. JavaScript Koans
  2. 회고

1. JavaScript Koans

  • javascript koans는 약 3주간의 학습을 했던 내용을 간단한 테스트 문제로 총 9개의 주제로 이루어져 있었다.
  • 최대한 풀어보고 헷갈리거나 이해가 안되는 것들은 console을 찍으면서 진행을 해보았다.

1-1) Types_1

"비교연산자 '==='은 두 값의 일치 여부를 엄격하게 검사한다"

1 === 1 // true
1 === '1' // false
  • 자료형 변환 없이 두 피연산자가 엄격히 같은지 판별해준다.

1-2) Let,Const

  • 변수를 선언할 때에는 let,const,var 를 사용할 수 있다.

  • var는 중복 선언이 가능하여 오륲가 발생할 수 있어서 let, const에 비해 잘 사용되지 않는다.

  • letconst의 차이는 재할당 여부이다. 코드의 가독성을 높이고 오류방지를 위해 고정값으로 const를 사용해주는 것이 좋다.

  • const로 선언된 변수에는 재할당이 금지된다.

  • const로 선언된 배열의 경우, 새로운 요소를 추가하거나 삭제할 수 있다.

  • const로 선언된 객체의 경우, 속성을 추가하거나 삭제할 수 있다.

1-3) Scope

  • scope는 변수의 값을 찾을 때 확인되는 곳을 말한다.
function () {
  let funcExpressed = 'it is function';
  
  typeof funcDeclared // 'function'
  typeof funcExpressed // 'string'
  
  function funcDeclared() {
      return 'this is a function declaration';
    }
  

1-4) ArrowFunction

  • 함수 표현식보다 단순하고 간결한 문법으로 만들 수 있는 방법이다.
let sum = (a, b) => a + b;

< 함수 func는 화살표(=>) 우측의 표현식을 평가하고, 평가 결과를 반환한다 >

  • 리턴을 생략할 수 있다.
  • 필요에 따라 소괄호를 붙일 수 있다.
  • 파라미터가 하나일 경우 소괄호 생략 가능.

1-5) Types_2

  • 원시 자료형은 각 값 자체에 대한 변경은 불가능하지만, 새로운 값으로 재할당은 가능하다.
  • 원시 자료형을 변수에 할당할 경우, 값 자체의 복사가 일어난다.
let overTwenty = true;
    let allowedToDrink = overTwenty;

    overTwenty = false;
    expect(overTwenty).to.equal(false);
    expect(allowedToDrink).to.equal(true);

    let variable = 'variable';
    let variableCopy = 'variableCopy';
    variableCopy = variable;
    variable = variableCopy;
    expect(variable).to.equal(variableCopy);
  • 참조 자료형의 데이터는 동적으로 변한다.

  • 참조 자료형을 변수에 할당할 경우, 데이터의 주소가 저장된다.

    const overTwenty = ['A', 'B', 'C'];
       let allowedToDrink = overTwenty;
    
       overTwenty.push('D');
       expect(allowedToDrink).to.deep.equal(overTwenty);
       overTwenty[1] = 'E';
       expect(allowedToDrink[1]).to.deep.equal(E[1]);
    `` ``````````

1-6) Array

  • Array의 method중에서는 slice는 배열의 값을 복사하여 새로운 배열을 리턴한다.
const arr = ['candy', 'butter', 'and', 'gum'];

arr.slice(0) = ['candy', 'butter', 'and', 'gum'];
// 위 코드는 원본을 건드리지 않고 arr전체를 복사한다

1-7) Object

  • this는 method를 호출한 시점에 method를 호출한 객체를 말한다.
  • this는 함수의 호출에 따라서 값이 달라지기도 한다.
let obj = {foo: function() {return this}};
function () {
    const megalomaniac = {
      mastermind: 'Brain',
      henchman: 'Pinky',
      getFusion: function () {
        return this.henchman + this.mastermind;
      },
      battleCry(numOfBrains) {
        return `They are ${this.henchman} and the` + ` ${this.mastermind}`.repeat(numOfBrains);
      },
    };

but! => 화살표 함수에서의 'this'는 자신을 감싼 정적 범위이다. ( 전역에서는 전역 객체를 가리킨다)

1-8) SpreadSyntax

  • 객체, 배열 등을 펼쳐주는 역활로 반복 가능한, 배열 문자열 또는 이터러블에 사용한다.

< 대상이 객체인 경우 >

const myObject1 = {
    laptop: 'MacBook Pro',
    tablet: 'iPad Pro'
}

const myObj2 = {...myObj1};

console.log(myObj1); // {laptop: "MacBook Pro", tablet: "iPad Pro"}
console.log(myObj2); // {laptop: "MacBook Pro", tablet: "iPad Pro"}

console.log(myObj1 === myObj2); // false

< 대상이 배열인 경우 >

const myArray1 = ['one', 'two', 'three', 'four', 'five'];

const myArray2 = [...myArray1];

console.log(myArray1); // ["one", "two", "three", "four", "five"]
console.log(myArray2); // ["one", "two", "three", "four", "five"]

console.log(myArray1 === myArray2); // false

1-9) Destructing

  • 구조 분해 할당 문법은 배열 혹은 객체에서 각각 값(value)이나 프로퍼티(property) 를 분해하여 손쉽게 별도의 변수에 담을 수 있도록 해준다.
let [a, b] = [10, 20];
console.log(a); // 10
console.log(b); // 20

< 배열을 분리한다 >

const array = ['I', 'can', 'do', 'it']

const [first, second] = array
    expect(first).to.eql('I')
    expect(second).to.eql('can')

    const result = []
    function foo([first, second]) {
      result.push(second)
      result.push(first)
      
      foo(array)
    expect(result).to.eql(['can', 'I'])
    }

< rest/spread 문법을 배열 분해에 적용할 수 있다 >

const array = ['I', 'can', 'do', 'it']
    const [start, ...rest] = array
    expect(start).to.eql('I')
    expect(rest).to.eql(['can', 'do', 'it'])

2. 회고

오늘은 페어랑 함께 'javascript koans' 과제를 진행하였다. 약 3주간의 학습을 했던 내용을 간단한 테스트 문제로 총 9개주제로 이뤄진 문제를 풀어보았는데 생각보다 쉽지는 않았다. 복습임에도 불구하고 막혔던 부분도 존재하였고 (scope에 클로저함수라는건 안비밀...) 쉽게쉽게 풀려나가는 부분도 있었다. section1이 끝나가는 도중에 복습을 하며 리마인드 한다는 것이 꽤나 유익하고 좋았던 것 같다. 오늘 과제를 진행하였던걸 바탕으로 막혔던 부분은 이번 연휴에 시간을 내서 다시 한 번더 복습을 해봐야겠다!

profile
LV2 프론트엔드 엔지니어

0개의 댓글