Javascript/Javascript

[Javascipt] ECMAScript 2015(ES6) 그 이후 - (1) 연산자

금요일인줄 2025. 5. 27. 09:00
728x90
반응형

 

 

자바스크립트의 혁명이라 할 수 있는 ECMAScript 2015(ES6) 이후 추가된 자바스크립트 최신 문법 중 자주 이용할 만한 기능들을 추려 정리해 보려 한다.

 

들어가기에 앞서 😡은 과거의 문법을, 😊은 최신 문법을 의미한다는 점을 참고해 봐주시길 바란다.

 

 

 

지수 연산자

  • 간단하게 곱셈 기호를 두 번 쓰면 제곱으로 처리할 수 있게 됨.
2**10 // 😊 1024

 

 

 


 

 

Numeric separators

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

 

 


 

 

Tagged Templated Literal

  • 함수의 실행을 탬플릿 리터럴로 구현
const tag = (...args) => console.log(args);

tag`너의 정체가 도대체 뭐니?`; 
// [["너의 정체가 도대체 뭐니?", raw: ['너의 정체가 도대체 뭐니']]]


const a = '정체가';
const b = '뭐니?';

tag`너의 ${a} 도대체 ${b}`; 
// [['너의 ', ' 도대체 ', ' ', raw: ['너의 ', ' 도대체 ', '']], '정체가', '뭐니?']

 

 


 

Shorthand property names

  • 프로퍼티 이름과 value 값의 변수명이 동일할 때에는 하나로 생략 가능
const ellie1 = {
  name: 'Ellie',
  age: '18',
};
const name = 'Ellie';
const age = '18';


// 😡
const ellie2 = {
  name: name,
  age: age,
};

// 😊
const ellie3 = {
  name,
  age,
};

 

 


 

 

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); // 🐶 😽

 

 


 

 

Spread Syntax

  • 전개 연산자
  • 객체나 배열 안의 요소들을 펼쳐 복사에 이용. 자기 자신 객체, 배열은 영향을 받지 않음.
  • 함수의 arguments에 쓰이면 나머지 연산자로 이용됨. 나머지 인자 값들을 모아 배열로 생성.
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: '🐶' }

 

 


 

 

Short circuit

  • 단축 평가.
  • and 연산자와 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) // '이름없음'

 

명제로 정리해 보자면 다음과 같다.
- 왼쪽 값이 Truthy하면 왼쪽 값을 리턴한다.
- 왼쪽 값이 Falsy하면 오른쪽 값을 리턴한다.

 

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) // null


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

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

console.log(f); // 4

 

 

&& 연산자

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); // '킹크랩'

 

정리해 보면 다음과 같다.
- 왼쪽 값이 Truthy하면 오른쪽 값이 리턴된다. 만약 오른쪽 값이 없으면 undefined나 null.
- 왼쪽 값이 Falsy하면 왼쪽 값이 리턴된다.
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"); // undefined

 

 


 

 

Nullish Coalescing Operator

  • ?? 문법
  • 거짓의 판단을 유연하게 판단. 그냥 심플하게 값이 있고 없고로 판단하는 것.
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); // 0

 

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'

 

 


 

 

 

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 &&= newName

 

let oldName;
let newName = 'newPerson';	

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

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

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

 

 


 

 

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: 25
function config(options) {
  options.duration ??= 100;
  options.speed ??= 25;
  return options;
}

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

 

 

 

 

 

728x90
반응형