본문 바로가기
Spring/JavaScript+Jsp(HTMl)

[JavaScript] 최신 문법 연산자 관련 정리 (ES6 ~ ES13)

by snow_hong 2024. 3. 4.

ECMASript 2015(ES6) 이후 추가된 자바스크립트 최신 문법 중 연산자 관련 문법 기능들을 추려 정리한 내용이다.

 


1. 연산자

1-1. 지수 연산자

2**3 //8
  • 곱셈 기호를 두 번 쓰면 제곱으로 처리된다.

1-2. Numeric separators

  • 100000000000000과 과 같은 단위가 큰 숫자의 가독성을 높일 수 있게 언더바(_)로 단위를 구분할 수 있는 표현이 허용된다.
  • ex) 1_000_000_000_000과 같이 천 단위로 끊어서 표기를 하는 것이 가능하기 때문에 0의 개수를 일일이 세어 볼 필요 없이 1000억이라는 숫자임을 조금 더 쉽게 알 수 있다.
  • 구분자(_)는 임의의 위치에 맘대로 삽입 가능하다.
  • 그냥 구분자 표현하는 것일뿐 구분자가 있다고 해서 숫자가 달라지거나 그러지 않는다.
console.log(1_000_000_000 + 10_000); // 1000010000
console.log(1_00_00_00 + 10_0); // 1000100
console.log(1_0_0_0); // 1000

1-3. Tagged Template Literal

  • 함수의 실행을 템플릿 리터럴로 구현
const text = (...args) => console.log(args);
 
text`너의 정체가 도대체 뭐니?`; 
// [["너의 정체가 도대체 뭐니?", raw: ['너의 정체가 도대체 뭐니']]]
 
 
const a = '정체가';
const b = '뭐니?';
 
test`너의 ${a} 도대체 ${b}`; 
// [['너의 ', ' 도대체 ', ' ', raw: ['너의 ', ' 도대체 ', '']], '정체가', '뭐니?']

1-4. Shorthand property names

  • 프로퍼티 이름과 value값의 변수이름과 동일할때는 하나로 생략 가능
const brie1 = {
  name: 'brie',
  age: '18',
};
const name = 'brie';
const age = '18';
 
 
// 옛날 코드
const brie2 = {
  name: name,
  age: age,
};
 
// 신규 트렌드 코드
const brie3 = {
  name,
  age,
};

-------------------------------------
let room = {
  number: 23,
  name: "hotel",
  toJSON() {
    return 9999;
  }
};
 
let meetup = {
  title: "Conference",
  room
};

console.log(meetup);

1-5. Destructuring Assignment

  • 구조분해 문법
  • 객체, 배열안의 원소값들을 바깥 변수로 한번에 빼서 사용하기 위한 기법
// object
const student = {
  name: 'Anna',
  level: 1,
};
 
 
// 옛날코드
const name = student.name;
const level = student.level;
console.log(name, level); // Anna 1
 
//신규코드
const { name, level } = student;
console.log(name, level); // Anna 1
 
const { name: studentName, level: studentLevel } = student;
console.log(studentName, studentLevel); // Anna 1
// array
const animals = ['🐶', '😽'];
 
 
// 구버전
const first = animals[0];
const second = animals[1];
console.log(first, second); // 🐶 😽
 
// 신버전
const [first, second] = animals;
console.log(first, second); // 🐶 😽

1-6. Spread Syntax

  • 전개연산자
  • 객체나 배열의 안의 요소들을 펼쳐 복사에 이용. 자기 자신 객체, 배열은 영향 안받음
  • 함수의 아규먼트에 쓰이면, 나머지 연산자로 작용. 나머지 인자값들을 모아 배열로 생성
const obj1 = { key: 'key1' };
const obj2 = { key: 'key2' };
const array = [obj1, obj2];
 
// array copy
const arrayCopy = [...array];
console.log(arrayCopy); // [ { key: 'key1' }, { key: 'key2' } ] 
 
const arrayCopy2 = [...array, { key: 'key3' }];
obj1.key = 'newKey'; // array배열은 래퍼런스 값을 갖고있는 배열이다. 그래서 전개연산자로 복사하여도 
                     // 레퍼런스 변수는 복사로 취급하지만, 그걸 잇는 주소연결은 똑같다.
console.log(array); // [ { key: 'newKey' }, { key: 'key2' } ]
console.log(arrayCopy2); // [ { key: 'newKey' }, { key: 'key2' }, { key: 'key3' } ]
 
// object copy
const obj3 = { ...obj1 };
console.log(obj3); // { key: 'newKey' }
 
// array concatenation
const fruits1 = ['🍑', '🍓'];
const fruits2 = ['🍌', '🥝'];
const fruits = [...fruits1, ...fruits2];
console.log(fruits); // [ '🍑', '🍓', '🍌', '🥝' ]
 
// object merge
const dog1 = { dog: '🐕' };
const dog2 = { dog: '🐶' };
const dog = { ...dog1, ...dog2 };
console.log(dog); // { dog: '🐶' }

 


 

 

1-7. Short circuit

  • 단축 평가.
  • and연산자와 or연산자 특성을 이용해 반환값을 결정하는 기법

1-7-1. || 연산자 (OR 연산자)

const seaFood = {
  name: "박달대게"
};

function getName(fish) {
  /*if(!fish) {
    return '이름없음'
  }
  return fish;*/
  return fish || '이름없음' // 만약 fish가 null이라면 대신 or '이름없음'을 리턴
}

const name = getName(seaFood)
console.log(name) // {name : 박달대게}

const name2 = getName()
console.log(name2) // '이름없음'Copy
  • fish 가 True(참) 이면 왼쪽 값인 fish 를 return 하고
  • fish 가 False(거짓) 이면 오른쪽 값인 '이름없음' 을 return 한다.

Tip

명제로 정리해보다면 아래와 같다.
- 왼쪽 값이 True 하면 왼쪽 값을 리턴한다.
- 왼쪽 값이 False 하면 오른쪽 값을 리턴한다.

console.log(false || 'hello') // 'hello'
console.log('' || 'hello') // 'hello'

console.log('트루' || 'hello') // '트루'
console.log(1 || 'hello') // 1

console.log('hello1' || false) // 'hello1'
console.log('hello2' || NaN) // 'hello2'

console.log(null && false) // false
console.log(undefined || null) // nullCopy


var a;
var b = null;
var c = undefined;
var d = 4;
var e = 'five';

var f = a || b || c || d || e; // null, undefiend, 빈값은 false하다

console.log(f); // 4Copy
 

 

1-7-2. && 연산자 (AND 연산자)

const seaFood = {
  name: "킹크랩"
}

function getName(fish) {
  /*if(fish) {
    return fish.name;
  }
  return undefined*/
  return fish && fish.name // 만약 fish가 참이면, 우측값을 리턴한다.
}

const name = getName(seaFood);
console.log(name); // '킹크랩'Copy

fish 도 True 하고 fish.name 또한 True 하다면 오른쪽의 값을 return 한다.

Tip

명제로 정리해보다면 아래와 같다.
- 왼쪽 값이 True(참) 이면 오른쪽 값이 리턴된다.
- 만일 오른쪽 값이 없으면 undefined나 null
- 왼쪽 값이 False(거짓) 이면 왼쪽 값이 리턴된다.

console.log(true && "hello"); // 'hello'
console.log(null && undefined); // null
console.log(undefined && "hello"); // undefined
console.log("hello" && null); // null
console.log("hello" && "bye"); // bye
console.log(null && "hello"); // null
console.log(undefined && "hello"); // undefinedCopy

1.8 - Nullish Coalescing Operator

  • ?? 문법
  • 거짓의 판단을 유연하게 판단. 그냥 심플하게 값이 있고 없고로 판단(undefined 판단)
var named = 'Ellie';
var userName = named || 'Guest';
console.log(userName); // Ellie

var named = null;
var userName = named || 'Guest';
console.log(userName); // Guest


// 구 방법
var named = '';
var userName = named || 'Guest'; // 논리값은 빈값도 false로 판단
console.log(userName); // Guest

var num = 0;
var message = num || 'Hello'; // 논리값은 0은 false로 판단
console.log(message); // Hello

// 신규 방법
var named = '';
var userName = named ?? 'Guest'; // 그냥 심플하게 값이 있고 없고로 판단. 빈칸도 결국 값이 빈칸인 것이다.
console.log(userName); // ''

var num = 0;
var message = num ?? 'Hello'; // 0도 결국 값이 0인것
console.log(message); // 0Copy
let a = null ?? 'hello';
let b = '' ?? true;
let c = false ?? true;
let d = 0 ?? 1;
let e = undefined ?? 'world';

console.log(a); // 'hello'
console.log(b); // ''
console.log(c); // false
console.log(d); // 0
console.log(e); // 'world'Copy

1-9. Logical Operators and Assignment Expressions

  • &&=, ||=
  • 위의 Short circuit 단축평가 ||, && 의 연산자의 += *= 같은 버젼
let oldName = 'oldPerson';
let newName = 'newPerson';	

// -- if문을 통한 값 대입
if(oldName) {
   oldName = newName;   
}

// && 연산자를 활용한 값 대입 
oldName && (oldName = newName);

// Logical Operators and Assignment Expressions (&&) 를 통한 값 대입
oldName &&= newNameCopy
let oldName;
let newName = 'newPerson';	

// -- if문을 통한 값 대입
if(!oldName) {
   oldName = newName;   
}

// || 연산자를 활용한 값 대입 
oldName || (oldName = newName);

// Logical Operators and Assignment Expressions (||) 를 통한 값 대입
oldName ||= newNameCopy

 

1-10. Logical nullish assignment

  • ??=
  • x ??= y 에서 x가 null 이나 undefined 일 경우 y를 대입
const a = { duration: 50 };

// a.duration = a.duration ?? 10; 의 단축 버전
a.duration ??= 10; // a의 속성에 duration 속성이 있으니 10은 무시
console.log(a.duration); // expected output: 50

a.speed ??= 25; // a의 속성에 speed 라는 키가 없으니 25가 들어감
console.log(a.speed); // expected output: 25Copy
function config(options) {
  options.duration ??= 100;
  options.speed ??= 25;
  return options;
}

config({ duration: 125 }); // { duration: 125, speed: 25 }
config({}); // { duration: 100, speed: 25 }

 


[ 참고 및 출처 사이트]

 

[JS] 🚀 자바스크립트 최신 문법 정리 - ECMAScript 2022

JavaScript 최신 문법 정리 (ES6 ~ ES13) 자바스크립트의 혁명이라 할수 있는 ECMASript 2015(ES6) 이후 추가된 자바스크립트 최신 문법 중 자주 이용할것 같은 기능들을 추려 정리해본다. 정말 편한 기능들

inpa.tistory.com

 

728x90

댓글