Basic operators, maths
Terms: "unary","binary","operand"
let x = 1, y = 3;
x = -x;
let result = y - x;
- An operand : what operators are applied to, like '1', '3'
- An operator is 'unary' : it has a single operand, like '-' reverses the sign of a number
- An operator is 'binary' : it has two operands, like 'y - x'
Maths
- Addition +
- Subtraction -
- Multiplication *
- Division /
- Remainder %
- the remainder of the integer division
- Exponentiation **
- Raises "a" to the power of "b"
String concatenation with binary +
let str = "Hello, " + "string";
alert(str);
alert( '1'+2 )
- It merges them, if the binary + is applied to strings
- Converted all to a string, if any of the operands is a string
- Doesn't matter whether the first operand is a string or the second one
alert( 2+2+'1' )
alert( '1'+2+2 )
- Operators work one after another
- The first sums two numbers, so it returns 4, then the next adds the string
- But, the first operand is a string, the result of '1'+2 is a string, then the next adds the string
- cf. The binary + is the only operator that supports string in such a way
Numeric conversion, unary +
let x = 1;
alert( +x );
alert( +true )
alert( +"" );
- The plus operator + applied to a single value, doesn't do anything to numbers
- If the operand is not a number, the unary plus converts it into a number
let x = "2";
let y = "3";
alert( x + y );
alert( +x + +y );
- unary pluses are applied first, convert string to numbers, and then the binary plus sums them up
Operator precedence
- If an expression has more than one operator, the execution order is defined by operator precedence
Precedence | Name | Sign |
---|
14 | unary plus | + |
14 | unary negation | - |
13 | exponentiation | ** |
12 | multiplication | * |
12 | division | / |
11 | addition | + |
11 | subtraction | - |
- Note that unary operators are higher than corresponding binary ones
Assignment
- An assignment = is the very low priority of 2
- The calculations are done first and then the = is evaluated
Assignment = return a value
- All operators in JavaScript return a value
- if 'x = value' calls, the value into x and then returns it
Chaining assignments
let a, b, c;
a = b = c = 2 + 2;
- Chained assignments evaluate from right to left
- First, the rightmost expression (2+2) is evaluated
- Assigned to the variables on the left: c, b and a
Modify-in-place
let n = 2;
n = n + 2;
n = n * 2;
- Short "modify-and-assign" operators exist for all arithmetical and bitwise operators
Increment/decrement
let count = 2;
count++;
count--;
- Increasing or decreasing a number by one
- Notice that this operations can only be applied to variables, not a number
- The operators ++ and -- can be placed either before or after a variable
- The prefix form : would like to increase a value and immediately use the result of the operator
- The postfix form : would like to increment a value, but use its previous value
- It's precedence is higher than most other arithmetical operations
Bitwise operators
- Bitwise operators treat arguments as 32-bit integer numbers and work on the level of their binary representation
- AND(&)
- OR(|)
- XOR(^)
- NOT(~)
- LEFT SHIFT(<<)
- RIGHT SHIFT(>>)
- ZERO-FILL RIGHT SHIFC(>>>)
Comma
let a = (1+2, 3+4);
alert(a);
- It's used to write shorter code
- Only the result of the last one is returned
- Notice that comma has a very low precedence
Comparisons
- Greater/less than: a > b, a < b
- Greater/leess than or equals: a >= b, a <= b
- Equals : a == b
- Not equals : a != b
Boolean is the result
- All comparison operators return a boolean value
- true : "yes", "correct" or "the truth"
- false : "no", "wrong" or "not the truth"
String comparison
- Uses the called "dictionary" or "lexicographical" order
- Strings are compared letter-by-letter
alert( 'Z' > 'A' );
alert( 'Glow' > 'Glee' );
- Compare the first character of both strings
- And then, compare the first character from the first string is greater than the other string's
- If both string's first characters are the same, compare the second characters the same way
- Repeat until the end of either string
- cf. Not a real dictionary, but Unicode order
Comparison of different types
alert ( '2' > 1 );
alert ( '01' == 1 );
- When comparing values of different types, JavaScript converts the values to numbers
Strict equality
alert ( 0 == false );
alert ( 0 === false );
- A strict equality === (triple equals) : checks the equality without type conversion
- If the types differ, 'false' is returned
- There are also a "Strict non-equality !=="
Comparison with null and undefined
alert( null === undefined );
alert( null == undefined );
- Converted to numbers
- "null" becomes 0
- "undefined" becomes NaN
null vs 0
alert( null > 0 );
alert( null == 0 );
alert( null >= 0 );
- An equality check == for "undefined" and "null" is defined without any conversions
- They equal each other and don't equal anything else
- That's why null == 0 is false
An incomparable undefined
- The value "undefined" shouldn't be compared to other values, always false
Avoid problems
- Be exceptional care for any comparison with 'undefined/null', except the strict equality
- Don't use comparisons >=, >, <, <= with a variable which may be 'undefined/null'
- checking for 'undefined/null' separately is a good idea
Conditional branching: if, '?'
The 'if' statement
let year = prompt('ECMAScript-2015는 몇 년도에 출판되었을까요?', '');
if (year == 2015) alert('정답입니다!');
- if(...) : 괄호 안의 조건문 평가하여, true면 코드 블록 실행
- 실행문이 한 줄이면 {} 생략 가능하지만 권장하지 않음
Boolean conversion
if (0) {
...
}
if (1) {
...
}
let cond = (year == 2015);
if (cond) {
...
}
- if문은 괄호 안의 조건문을 평가하고, 그 결과를 불린값으로 변환
- cf. 숫자 0, "", null, undefined, NaN은 모두 false
The 'else' clause
if (year == 2015) {
alert('정답입니다!');
} else {
alert('오답입니다!');
}
- else : 조건문이 false인 경우에 실행
- 선택 사항(생략 가능)
Several condifions: 'else if'
if (year < 2015) {
alert( '숫자를 좀 더 올려보세요.' );
} else if (year > 2015) {
alert( '숫자를 좀 더 내려보세요.' );
} else {
alert( '정답입니다!' );
}
- else if : 특정한 조건 여러 개를 처리하는 경우
- year가 2015 이상, 이하도 아닌 경우가 정답
Conditional operator '?'
let result = condition ? value1 : value2;
- 물음표 연산자(question mark) = 삼항 연산자(ternary)
- condition이 true면 value1, false면 value2 반환
- 조건문(condition)의 괄호는 생략 가능하지만, 가독성을 위해 사용 권장
- cf. 비교 연산자 자체가 true/false를 반환하므로 물음표 연산자를 사용하지 않아도 됨
Multiple '?'
let age = prompt('Enter your age', 18);
let message (age < 3) ? 'Hello, baby?' :
(age < 18) ? 'Hello!' :
(age < 100) ? 'Greethings!' :
'What an unusual age!';
alert( message );
- 물음표 연산자를 여러 개 연결하여 복수 조건 처리 가능
- if-else if문으로도 가능
Non-traditional use of '?'
- 물음표 연산자는 조건에 따라 반환 값을 다르게 할당하기 위해 사용
- if문 대신 물음표를 사용하는 경우 사용 목적을 잘 고려해야 함
- 여러 줄로 나뉘어 세로로 작성된 코드가 가독성이 좋음
Logical operators
|| (OR)
alert( true || true );
alert( false || true );
alert( true || false );
alert( false || false );
- 피연산자가 모두 false인 경우를 제외하고는 항상 true
- if문에서 자주 사용됨
|| (OR) finds the first truthy value
let result = value1 || value2 || value3
- OR 연산자와 피연산자가 여러 개인 경우
- 왼쪽부터 피연산자를 불린형으로 변환하여 true인지 평가
- true인 경우 연산을 멈추고 해당 피연산자의 변환 전 원래 값을 반환 (= 첫 번째 truthy 반환)
- 모든 피연산자가 false인 경우, 마지막 피연산자 반환
OR 연산자 활용
let firstName = "";
let lastName = "";
let nickName = "Hello";
alert( firstName || lastName || nickName || "익명" );
- 변수 또는 표현식에서 첫 번째 truthy 얻기
- 실제 값이 들어있는 변수를 반환 (nickName)
- 만약 모두 값이 없는 경우에는 "익명" 반환
true || alert("not printed");
false || alert("printed");
- 단락 평가 (short circuit evaluation)
- truty를 만나면 나머지 값들은 건드리지 않은 채 멈춤
- 조건이 false일 때만 명령어를 실행할 때 주로 쓰임
&& (AND)
alert( true && true );
alert( false && true );
alert( true && false );
alert( false && false );
- 피연산자가 모두 true인 경우를 제외하고는 항상 false
&& (AND) finds the first falsy value
let result = value1 && value2 && value3
- AND 연산자와 피연산자가 여러 개인 경우
- 왼쪽부터 피연산자를 불린형으로 변환하여 false인지 평가
- false인 경우 연산을 멈추고 해당 피연산자의 변환 전 원래 값을 반환 (= 첫 번째 falsy 반환)
- 모든 피연산자가 true인 경우, 마지막 피연산자 반환
- AND 연산자에도 여러 개의 피연산자를 전달할 수 있음
- && (AND) 연산자가 || (OR)보다 우선 순위가 높음
! (NOT)
let result = !value;
- NOT 연산자는 인수를 하나만 받을 수 있음
- 피연산자를 불린형으로 변환
- 변환한 값의 역을 반환
alert( !true );
alert( !0 );
alert( !!"non-empty string" );
alert( !!null );
- NOT을 두 번 연달아 사용하면(!!) 값을 불린형으로 변환
- Boolean()와 동일한 결과 반환
- 모든 논리 연산자 중에서 우선 순위가 가장 높음
Nullish coalescing operator '??'
let x = a ?? b;
- '값이 할당된' 변수 판별
- a가 null도 아니고 undefined도 아니면 a
- 그 외에는 b
let height = height ?? 100;
Comparison with ||
- ||는 첫 번째 truthy 값을 반환
- ??는 첫 번째 정의된(defined) 값을 반환
let x = 0;
alert (x || 100);
alert (x ?? 100);
- ||는 x=0을 falsy한 값으로 취급하여 null이나 undefined로 처리하고, 100을 반환
- ??는 정확하게 null이나 undefined일 경우에만 처리하기 때문에 x=0라는 값을 truthy로 판단하여 반환
Precedence
- 우선 순위는 대부분의 연산자들보다 낮고, =와 ?보다는 높음
- 복잡한 표현식에서 필요한 경우 () 추가하는 것이 좋음
- 괄호 없이 &&나 ||와 함께 사용할 수 없음
"JavaScript Fundamentals", by Ilya Kantor, 2007-2022, https://javascript.info/first-steps