🦎 JavaScript

[JS] 다른 연산자의 우선순위

하나둘세현 2023. 1. 22. 00:14
728x90

const now = 2037;
const ageJonas = now - 1991;
const ageLisa = now - 2018;

console.log(now - 1991 > now - 2018);

왜 빼기 연산자가 비교 연산자보다 먼저 실행될까? 

자바스크립트는 잘 정의된 연산자를 우선 순위로 갖는다. 따라서 기본적으로 연산자가 실행되는 순서이다. 

 

왼쪽 → 오른쪽

console.log(now - 1991 > now - 2018);

오른쪽 → 왼쪽

let x, y;
x = y = 25 - 10 - 5;
console.log(x, y);

뺄셈이 먼저 시작한 이유는 우선순위가 높기 때문이다. x = y 랑 값이 같다.  y는 정의되지 않는다. 그 이유는 let x,y;에서 빈 변수로 선언했기 때문이다. 

 

우선 순위가 가장 높은 항목은 그룹화이다. 기본적으로 괄호를 사용한다. 

 

더 자세한 내용은 하단의 링크를 통해 확인할 수 있다. 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

 

Operator precedence - JavaScript | MDN

Operator precedence determines how operators are parsed concerning each other. Operators with higher precedence become the operands of operators with lower precedence.

developer.mozilla.org

 

728x90

'🦎 JavaScript' 카테고리의 다른 글

[JS] if / else 문  (0) 2023.01.23
[JS] 문자열  (0) 2023.01.23
[JS] 기본 연산자  (0) 2023.01.21
[JS] Blooleans(불리언)  (0) 2023.01.19
[JS] Variables (변수) | let | const | var  (0) 2023.01.12