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
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
한번에 하나의 일
만 하게 한다.동사
로 만든다.// default 를 unknown 으로 지정
function showMessage(message, from = "unknown"){
console.log(`${message} by ${from}`);
}
showMessage("Hello");
// Hello from unknown
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
함수는 hoisting
되므로, 선언이 자동으로 위로 올라간다.(function sayHello(){
console.log("Hello");
})();
// Hello
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);
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
class Practice{
publicField = 2;
#privateField = 9;
}
const practice = new Practice();
console.log(practice.publicField); // 2
console.log(practice.privateField); // undefined
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/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.
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
// 방법 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
console.log(han.name); // han
console.log(han["name"]); // han
// 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
// 느리게 받는 방법
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);
const han = { name: "han", gender: "male" };
console.log("name" in han); // true
console.log("hobby" in han); // false
// 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
// 예시
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