[ TIL ] - JS 기초 문법 정리

Gorae·2021년 7월 30일
0

(TIL) Javascript

목록 보기
3/3
post-thumbnail
https://youtu.be/_DLhUBWsRtw 드림코딩 by 엘리 유튜브 참고

1. 자료형

(1) var 를 쓰면 안되는 이유

  • var 는 hoisting 이 적용되므로, 선언도 전에 호출되거나 값이 할당돼도 에러가 나지 않는다.
  • let 이 있으므로 굳이 위험부담을 무릅쓰며 쓸 필요가 없다.

(2) js 는 dynamically typed language

  • 처음 정해진 타입이 계속 바뀔 수 있는 언어이다.(런타임에서 타입이 정해진다.)
let text = "hello"; // string
text = 1; // number

text = "3" + 5;
console.log(`${typeof text}, text`); // string, 35

text = "10" / "2";
console.log(`${typeof text}, text`); // number, 5

(3) 빠르게 훑는 자료형

number type

  • js는 C언어 등과 달리 다양한 수 타입(int, long, float..)이 number type 하나로 통칭된다.
  • 이는 Typescript 에서도 마찬가지다.
  • number 타입을 0 으로 나눴을 때 Infinity, string을 숫자로 나눴을 때 NaN 타입으로 나타난다.
  • 예외) 엄청나게 큰 숫자는 뒤에 'n'을 붙여서 bigint 타입으로 나타낸다.

boolean

  • false : 0, null, undefined, NaN, ''(빈 문자열)
  • true : false 로 간주되는 값 이외의 모든 값

undefined / null

  • undefined 는 값이 없는 상태, 지정되지 않은 상태
  • null 은 null 이라는 값이 있는 상태
let x = null;
console.log(typeof x); // null
//
let x;
console.log(typeof x); // undefined

Symbol

  • 우선순위 식별자가 필요할 때 사용
  • 같은 값, 같은 타입이라도 고유하게 식별
const x = Symbol("hi");
const y = Symbol("hi");
console.log(x===y); // false

2. 함수

  • 함수는 한번에 하나의 일만 하게 한다.
  • 함수명은 동사로 만든다.

(1) 파라미터 옆에 default 값을 지정해 전달할 수 있다.

// default 를 unknown 으로 지정
function showMessage(message, from = "unknown"){
    console.log(`${message} by ${from}`);
}
showMessage("Hello");
// Hello from unknown

(2) 파라미터에 "...args"으로 배열 전달을 나타낼 수 있다.

function printAll(...args){
  // 방법 1
  for(let i=0; i< args.length; i++){
      console.log(args[i]);
    }
  // 방법 2
  for(const arg of args){
      console.log(arg);
  }
}
printAll("How", "are", "you");
// How
// are
// you

(3) 함수는 선언 전에 호출되어 사용될 수 있다.

  • 함수는 hoisting 되므로, 선언이 자동으로 위로 올라간다.

(4) 함수는 선언과 동시에 사용할 수 있다.(IIFE)

  • IIFE(immediately Invoked Function Expression)
(function sayHello(){
    console.log("Hello");
})();
// Hello

3. 클래스

(1) 클래스 선언 / 오브젝트 생성

  • 클래스 선언

Class Person {
//constructor
  constructor(name, age){
  // fields
    this.name = name;
    this.age = age;
  }
  //
  //method
  speak(){
      console.log(`${this.name}: hello!`);
  }
}
  • 오브젝트 생성

const hyun = new Person("hyun", 11);

(2) getter / setter

  • 나이를 음수로 입력해버리는 등의 일을 방지하기 위해, getter 와 setter 가 필요한 것이다.
class User {
	constructor(firstName, lastName, age){
    	this.firstName = firstName;
	this.lastName = lastName;
      	this.age = age;
    }
	
  // getter - constructor 의 'this.age' 가 getter 호출
  	get age(){
      // age 와 구분하기 위해 _age로 작성한다.
          return this._age;
    }
  // setter - constructor 에서 this.age 로 받은 age 가 value 가 된다
  	set age(value){
      	// 에러 조건을 설정하여 처리할 수 있다.
          this._age = value < 0? 0 : value;
    }
}
const chan = new User("Chan", "Bang", -1);
console.log(chan.age); // 0

(3) public/private field

  • class 내에서 constructor 없이, field 설정을 할 수 있다.
  • #을 붙이면 개발자만 볼 수 있는 private field 설정이 된다.
class Practice{
    publicField = 2;
    #privateField = 9;
}

const practice = new Practice();
console.log(practice.publicField); // 2
console.log(practice.privateField); // undefined

(4) static

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static

  • 오브젝트에 상관 없이 클래스 자체에 연결된 static으로 만들어 사용할 수 있다.
  • 클래스.메소드(), 클래스.변수 형식으로 오브젝트에 상관없이 사용할 수 있다.
class ClassWithStaticMethod {
  static staticProperty = 'someValue';
  static staticMethod() {
    return 'static method has been called.';
  }
}
console.log(ClassWithStaticMethod.staticProperty);
// someValue
console.log(ClassWithStaticMethod.staticMethod());
// static method has been called.

(5) 상속 / 다양성

  • extends 를 사용하여, 동일한 코드를 반복하지 않고 재사용할 수 있다.
class Shape {
  constructor(w, h, color){
    this.w = w;
    this.h = h;
    this.color = color;
    }
  draw(){
    console.log(`drawing ${this.color} tree`);
  }
  getArea(){
    return this.w * this.h;
  }
}

// Rectangle 클래스가 Shape 클래스 상속
class Rectangle extends Shape{}

// rectangle 오브젝트 생성
const rectangle = new Rectangle(50, 50, 'blue');
rectangle.draw(); // drawing blue tree
  • 상속받은 클래스에서 함수를 수정하여 사용할 수 있다.
class Triangle extends Shape{
  // draw 함수를 수정한다
  // super.draw()는 부모의 함수를 그대로 사용하는 것이다
  draw(){
    super.draw();
    console.log(`yeah!`);
  }
  // getArea 함수를 수정한다
  getArea(){
    return (this.w * this.h / 2);
  }
}

const triangle = new Triangle(30, 20, 'yellow');
triangle.draw();
// drawing yellow tree
// yeah!
console.log(triangle.getArea()); // 30

4. 오브젝트

  • 오브젝트는 key(프로퍼티) 와 value(프로퍼티의 값) 의 집합체이다.

(1) 오브젝트 생성

// 방법 1. {} 이용하여 생성(object literal syntax)
const obj01 = {};
// 방법 2. 클래스 이용하여 생성(object constructor syntax)
const obj02 = new Object();

// 예시
const han = { name: "han", gender: "male" };

// 이미 생성된 오브젝트에 런타임에서 프로퍼티를 추가할 수 있다.
han.handsome = true;
console.log(han.handsome); // true

// 런타임에서 오브젝트 프로퍼티 삭제가 가능하다.
delete han.handsome;
console.log(han.handsome); // undefined

(2) 프로퍼티에 대한 2가지 접근

  • (1) dot 사용
  • key 이름을 정확히 알 때 사용한다.
console.log(han.name); // han
  • (2) [] 사용
  • key 값은 꼭 string 타입으로 적어야 한다.
console.log(han["name"]); // han
  • key 에 상응하는 value 를 실시간으로(동적으로) 받아야 할 때,
    코딩하는 현재 value에 대해 알지 못할 때 사용.
// obj.key를 사용하면 안되는 경우
function printValue(obj, key) {
  console.log(obj.key);
}
printValue(han, "name"); // undefined

// obj[key]를 사용하면 되는 경우
function printValue(obj, key) {
  console.log(obj[key]);
}
printValue(han, "name"); // han

(3) Constructor function

  • 프로퍼티 value 를 빨리 받기위해 constructor function 사용
  • 클래스 이전에 존재하던 문법이다.
// 느리게 받는 방법
const person1 = { name: "bin", age: 5 };
const person2 = { name: "minho", age: 7 };
const person3 = { name: "jin", age: 3 };

// 빠르게 받는 방법(constructor function)
function Person(name, age){
  this.name = name;
  this.age = age;
}
const person1 = Person("bin", 5);
const person2 = Person("minho", 7);
const person3 = Person("jin", 3);

(4) 자주 쓰는 오브젝트 문법

  • key in obj

    obj 안에 key 의 존재 유무 확인
const han = { name: "han", gender: "male" };

console.log("name" in han); // true
console.log("hobby" in han); // false
  • for..in / for..of

// 1. for..in
const han = { name: "han", gender: "male" };

for (key in han) {
  console.log(key);
}
// name
// gender

// 2. for..of - 배열의 값 리턴에 사용
const array = [1, 2, 3];
for(value of array){
  console.log(value);
}
// 1
// 2
// 3

(5) 오브젝트 복사

  • Object.assign 을 사용하여 복사할 수 있다.
// 예시
const user1 = { name: "bok", age: "20" };
const user2 = {}; // 빈 오브젝트 생성

Object.assign(user2, user1);
console.log(user2); // Object.assign(user2, user1);

// 더 간단하게 만들기
const user2 = Object.assign({}, user1);
console.log(user2); // Object.assign(user2, user1);
  • 여러 개를 섞어서 복사하면, 나중에 쓴 것으로 덮어씌워진다.
const peach = { color: "pink" };
const mango = { color: "yellow", size: "big" };
const mixed = Object.assign({}, peach, mango);
console.log(mixed.color); // yellow
profile
좋은 개발자, 좋은 사람

0개의 댓글