JavaScript 기초 지식 정리 (1)

SERI·2022년 5월 15일
0

JavaScript

  • 객체 기반 언어
    • 원시 타입을 제외한 나머지 모두 객체
  • 인터프리터 언어(단점 해결 ver. 빠름)
    • 인터프리터 장점(소스코드 즉시 실행)+컴파일러 장점(빠르게 동작하는 머신코드)
  • 데이터 타입 지정 X
  • 가장 먼저 use strict 써주기

🧺 변수

  • 위치(주소)를 기억하는 저장소
  • 메모리 주소에 접근하기 위해 사람 언어로 저장한 식별자

data type

  1. 원시타입 (single item) : 변경 불가능한 값. 값에 의한 전달.
  • number

  • string

    • 배열처럼 인덱스를 통해 접근 가능
    • 변경 불가능
let str = 'string';
str[0] = 'S';
console.log(str); // string

* 재할당은 가능!

let str = 'string';
str = 'String';
console.log(str); // 기존 문자열 변경이 아닌 새로운 문자열을 새롭게 할당
  • boolean

    • false : '', NaN, 0, null, undefined
      • null
        값이 없다는 것을 명시
        함수가 호출되었으나 유효한 값을 반환할 수 없을 때도 null 반환
        type of가 object로 나오니 ===로 타입 확인
      • undefined
        선언 됐으나 값을 할당하지 않은 변수, 존재하지 않는 프로퍼티
    • true : any other value
  • null

    • type of -> object
  • undefined

  • symbol

    고유 식별자가 필요할 때
    우선순위를 주고 싶을 때

<동일한 string이나 다른 심볼>
const symbol1=symbol('id');
const symbol2=symbol('id');
console.log(symbol1===symbol2) // false

<동일한 string이고 동일한 심볼을 만들고 싶을 >
const symbol1=symbol.for('id');
const symbol2=symbol.for('id');
console.log(symbol1===symbol2) // true

<symbol 출력 방법 .description!>
console.log(`hi, ${symbol1.description}`);
  1. 객체 타입 (box container)
  • object
 const seri = {name: 'seri', age: 9};
 seri.age = 5; // (const임에도 변경 가능)

let vs var

  • var 위험성 큼
    • hoisting
      어디에 선언했느냐에 상관 없이 선언을 해당 scope의 제일 위로 끌어올림
      값을 선언하기도 전에 할당, 출력이 가능
    • block scope 무시

const 사용 이유

  1. security
  2. thread safety
    : 여러 스레드들이 접근해 값을 변경하기도 함 이를 예방
  3. reduce human mistakes

const vs let
대부분의 변수는 const로 선언. 변경될 여지가 있는 변수만 let을 이용

변수의 이름

  • 문자, 숫자, $, _
  • 첫글자에 숫자 X
  • 예약어 X
  • 상수는 대문자
  • 변수명은 읽고 이해하기 쉽게

➗ 연산자

  • || / &&

    • 표현식이나 함수를 호출하는 무거운 것들은 뒤에 배치
      • ||은 true를 만나면 뒤는 검사하지 않고, &&는 false를 만나면 뒤를 검사하지 않음

  • ==

    • 암묵적 타입 변환을 통해 타입을 일치시킨 후 비교
    • 타입이 달라도 true
    • 부작용 多

  • ===

    • 타입, 값이 같으면 true


  • 주의

    • NaN === NaN // false
    • 0 === -0 // true

<object equality>
const apple1 = {name: 'apple'};
const apple2 = {name: 'apple'};
const apple3 = apple1;

console.log(apple1 == apple2); // false (ref가 다름)
console.log(apple1 === apple2); // false (ref가 다름)
console.log(apple1 === apple3); // true(ref가 같음)


console.log(0 == false); // T
console.log(0 === false); // F (0은 불리언 타입이 아님)
console.log('' == false); // T 
console.log('' === false); // F
console.log(null == undefined); // T
console.log(null === undefined); // F

🏃 함수

  • 함수도 객체
    • 프로퍼티를 가짐
function square(number) {
    return number * number
}

square.x = 10;
square.y = 20;

console.log(square.x, square.y); // 10 , 20
  • 자바스크립트 함수는 일급 객체

    • 무명의 리터럴로 표현 가능
    • 변수나 자료 구조(객체, 배열~)에 저장 가능
    • 함수의 parameter로 전달 가능
    • 반환 값으로 사용 가능

  • 함수 표현식 (function expression)

    • 함수명 생략 가능 (생략이 일반적)
    • 함수를 변수에 할당하면 변수는 함수명이 아닌 할당한 함수를 가리키는 참조값을 저장. 함수 호출시 함수를 가리키는 변수명 사용.
    • function declaration can be called earlier than it is defined. (hoisted)
    • function exprssion is created when the execution reaches it.
    • 함수 표현식에서 이름을 쓰는 경우
      • better debugging in debugger's stack traces
      • recursions
const print = function () {
    console.log('print');
};

print(); // print
const printAgain = print;
printAgain(); // print
  • call by value (premitive parameters)

    • 원시 타입 인수를 함수에 매개변수로 전달할 때 값을 복사해 함수로 전달
      • 매개변수를 통해 값이 변경돼도 원시 타입 값은 변경 X

  • call by reference (object parameters)

    • 함수 호출 시 객체의 참조값이 매개변수에 저장되어 함수로 전달
      • 매개변수를 통해 값이 변경되면 인수값도 변경
function changeVal(primitive, obj) {
    primitive += 100;
    obj.name = 'Kim';
    obj.gender = 'female';
}

var num = 100;
var obj = {
    name: 'Lee',
    gender: 'male'
};

changeVal(num, obj);

console.log(num); 
console.log(obj); // {name: 'Kim', gender: 'female'}

call by value 방식인 num은 그대로 100.
call by reference 방식인 obj는 값이 바뀐 걸 확인할 수 있다.

  • Callback 함수

    • 함수를 parameter로 전달. 상황에 맞을 때 이 함수를 불러 쓰는 것
function randomQuiz(answer, printYes, printNo) {
    if (answer === 'love you'){
        printYes();
    } else {
        printNo();
    }
}

const printYes = function () {
    console.log('yes');
}

const printNo = function () {
    console.log('no');
}

randomQuiz('wrong', printYes, printNo);
randomQuiz('love you', printYes, printNo);
  • arrow function (always anonymous)
// expression
const add = function (a,b) {
    return a+b;
}; 

// arrow function
const add = (a,b) => a + b;
// 인수가 하나라면 괄호 생략 가능
let sayHello = name => `Hello, ${name}`;

// 길어질 때는 {}를 써도 됨 그러나 return을 써줘야 한다
Const add = (a,b) => {
	// do something more
  return a * b;
};

  • Default parameters
function showMessage(message, from){
    console.log(`${message} by ${from}`);

}
showMessage('hi!');

// hi! by undefined

function showMessage(message, from = 'unknown'){
    console.log(`${message} by ${from}`);

}
showMessage('hi!');

// hi! by unknown

  • Early return, early exit
// BAD CASE
function upgradeUser(user) {
    if (user.point > 10) {
        // long upgrade logic...
    }
}

// GOOD CASE
function upgradeUser(user) {
    if (user.point <= 10) {
        return;
    }
    // long upgrade logic...
}

📦 클래스

  • 같은 집단에 속하는 속성과 행위를 정의한 것

  • template

  • declare once

  • no data in


    object

  • instance of a class

  • created many times

  • data in

  • 클래스 선언

class Person {

// constructor : 인스턴스를 생성 및 초기화하기 위한 메서드
constructor(name, age) {
    // fiels
    this.name = name;
    this.age = age;
}

    // methods
    speack() {
        console.log(`${this.name}: hello!`);
    }

}

// 새로운 오브젝트를 만들 때 new를 씀
const seri = new Person('seri', 3);
console.log(seri.name);
console.log(seri.age);
seri.speack();

  • getter setters
    방어적으로 데이터를 보호
// 필드: firstName, lastName, _age

class User {
 constructor(firstName, lastName, age) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
}
	// get은 값을 리턴
    get age() { 
        return this._age;
    }

    // set은 값을 설정하기 때문에 value를 받아와야 함
    set age(value) {
        this._age = value < 0 ? 0 : value;

    }
}
const user1 = new User('steve', 'Job', 5)
console.log(user1.age);

  • 상속
class Shape {
    constructor(width, height, color) {
        this.width = width;
        this.height = height;
        this.color = color;
    }

    draw() { 
        console.log(`drawing ${this.color} color of`);
    }

    getArea() {
        return this.width * this.height;
    }
}

// extends! Shape에서 정의한 fields와 methods가
자동적으로 Rectangle에 포함됨
class Rectangle extends Shape {}

//overwriting
class Triangle extends Shape {
    draw() {
        super.draw(); // 부모의 draw를 호출
        console.log('△');
        // overwriting한 draw 함수에서만 출력하게 됨
    }
}

const rectangle = new Rectangle(20, 20, 'blue');
rectangle.draw();
console.log(rectangle.getArea());

const triangle = new Triangle(20,20,'red');
triangle.draw();
console.log(triangle.getArea());

// class checking: instanceOf
// 왼쪽의 object가 오른쪽의 class를 통해 만들어진 것인지 체크하는 것
console.log(rectangle instanceof Rectangle); // t
console.log(triangle instanceof Rectangle); //f
console.log(triangle instanceof Triangle); //t
console.log(triangle instanceof Shape); //t
console.log(triangle instanceof Object); //t

// 자바스크립트에서 만든 모든 오브젝트, 클래스는 
자바스크립트의 오브젝트를 상속한 것이다.

🙋 오브젝트

  • 참조 타입
    • 실제값이 아닌 참조값으로 처리됨
  • object = {key : value};
  • 키와 값으로 구성된 프로퍼티들의 집합
  • 데이터를 의미하는 프로퍼티 + 데이터를 참조하고 조작하는 동작을 의미하는 메소드
    • 프로퍼티
      • 키 + 값
    • 메소드
      • 프로퍼티 값이 함수일 때 일반 함수와 구분하기 위해 메소드라 부름. 메소드는 객체에 제한되어 있는 함수.
  • 프로퍼티 or 메소드명 앞에 기술한 this => 인스턴스
  • this에 연결된 프로퍼티, 메소드는 public
  • 내에 선언된 변수는 private
  • 각 프로퍼티는 ,로 구분
  • 화살표 함수는 일반 함수와는 달리 자신만의 this를 가지지 X 화살표 함수 내부에서 this 사용하면 외부에서 값을 가져 옴

1. 오브젝트 만드는 방법 두 가지

1. object literal
const obj1 = {};
2. object constructor / 클래스를 이용해서 만드는 방법
const obj2 = new Object

2. 출력 함수

function print(person) {
    console.log(person.name);
    console.log(person.age);
}

const seri = { name: 'seri', age: 4 }; 
print(seri);

3. 뒤늦게 하나의 property 추가, 삭제 가능
(에러 발생하게 할 수 있음. 지양)

<추가>
seri.hasJob = true;
console.log(seri.hasJob);

<삭제>
delete seri.hasJob;
console.log(seri.hasJob); // undefined

4. object 접근 방법 두 가지

console.log(seri.name); 
// 그 키에 해당하는 값을 가져오고 싶을 때
console.log(seri['name']); 
// 정확하게 어떤 키가 필요한지 모를 때 runtime에서 결정될 때 이렇게 씀

// .name을 쓰는게 맞다 실시간으로 원하는 키의 값을 가져오고 싶을 땐 []
function printValue(obj, key) {
    console.log(obj[key]); // obj.key는 오류
}

printValue(seri, 'name'); // key는 항상 string 타입으로 전달

5. in operator: property existence check (key in obj)

console.log('name' in seri);
console.log('age' in seri);

6. for (key in obj)

  • 모든 키들을 출력
for (key in seri) {
    console.log(key);
}

7. for of

  • array의 모든 값들이 value에 할당되면서 순차적으로 값이 출력
const array = [1, 2, 4, 5];
for(value of array) {
    console.log(value);
}

8. object.assign

const user4 = {};
Object.assign(user4, user);
console.log(user4);

9. 추가, 삭제

  • 추가
car.color = 'black';
car['wheels'] = 4;
  • 삭제
delete car.color;

10. 단축 프로퍼티

const apple = {
	name, // name: name과 동일
    color : 'red',
    eat(){
    console.log('상큼')
    }
}

profile
절망의 계곡을 탈출하자

0개의 댓글