[The Modern JavaScript] The JavaScript language - JavaScript Fundamentals 2

둡둡·2022년 12월 22일
0

Modern-JavaScript

목록 보기
3/10

Basic operators, maths

Terms: "unary","binary","operand"

let x = 1, y = 3; // operand
x = -x; // x = -1, unary
let result = y - x; // 2, binary
  • 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); // Hello, string
alert( '1'+2 ) // "12"
  • 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' ) // "41", not "221"
alert( '1'+2+2 ) // "122", not "14"
  • 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 ); // 1
  
alert( +true ) // 1
alert( +"" ); // 0
  • 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 ); // "23"
alert( +x + +y ); // 5
  • 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
PrecedenceNameSign
14unary plus+
14unary negation-
13exponentiation**
12multiplication*
12division/
11addition+
11subtraction-
  • 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; // a, b, c = 4
  • 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 += 2;
n = n * 2; // n *= 2;
  • Short "modify-and-assign" operators exist for all arithmetical and bitwise operators
    • +=, *=, /=, -=, etc.

Increment/decrement

let count = 2;
count++; // 3
count--; // 2
  • 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); // (3+4=) 7  
  • 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' ); // true
alert( 'Glow' > 'Glee' ); // true
// 1. G is the same as G
// 2. l is the same as l
// 3. o is greater than e, stop here
  • 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 ); // true, string '2' becomes a number 2
alert ( '01' == 1 ); // true, string '01' becomes a number 1
  • When comparing values of different types, JavaScript converts the values to numbers

Strict equality

alert ( 0 == false ); // true
alert ( 0 === false ); // false, the types are different
  • 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 ); // false
alert( null == undefined ); // true
  • Converted to numbers
    • "null" becomes 0
    • "undefined" becomes NaN
null vs 0
alert( null > 0 ); // false
alert( null == 0 ); // false
alert( null >= 0 ); // true
  • 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 (year == 2015) {
	alert('정답입니다!');
	alert('축하드립니다.');
} */
  • if(...) : 괄호 안의 조건문 평가하여, true면 코드 블록 실행
    • 실행문이 한 줄이면 {} 생략 가능하지만 권장하지 않음

Boolean conversion

if (0) { // false, 실행되지 않음
  ...
}
  
if (1) { // true, 실행됨
  ...
}
  
// true/false 판별 값으로도 전달 가능
let cond = (year == 2015); 
if (cond) { 
  ...
}
  • if문은 괄호 안의 조건문을 평가하고, 그 결과를 불린값으로 변환
    • cf. 숫자 0, "", null, undefined, NaN은 모두 false

The 'else' clause

if (year == 2015) {
  alert('정답입니다!');
} else { // 2015 이외의 값을 입력한 경우
  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;
// let accessAllowd = (age > 18) ? true : false;
// let accessAllowd = age > 18;
  • 물음표 연산자(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 );   // true
alert( false || true );  // true
alert( true || false );  // true
alert( false || 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 || "익명" ); // Hello
  • 변수 또는 표현식에서 첫 번째 truthy 얻기
    • 실제 값이 들어있는 변수를 반환 (nickName)
    • 만약 모두 값이 없는 경우에는 "익명" 반환
true || alert("not printed");
false || alert("printed");
  • 단락 평가 (short circuit evaluation)
    • truty를 만나면 나머지 값들은 건드리지 않은 채 멈춤
    • 조건이 false일 때만 명령어를 실행할 때 주로 쓰임

&& (AND)

alert( true && true );   // true
alert( false && true );  // false
alert( true && false );  // false
alert( false && 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 ); // false
alert( !0 ); // true

alert( !!"non-empty string" ); // true
// = alert ( Boolean("non-empty string"); 
alert( !!null ); // false
// = alert ( Boolean(null) );
  • NOT을 두 번 연달아 사용하면(!!) 값을 불린형으로 변환
  • Boolean()와 동일한 결과 반환
  • 모든 논리 연산자 중에서 우선 순위가 가장 높음

Nullish coalescing operator '??'

let x = a ?? b;
// (a !== null && a !== undefined) ? a : b;
  • '값이 할당된' 변수 판별
    • a가 null도 아니고 undefined도 아니면 a
    • 그 외에는 b
// height가 null이나 undefined인 경우, 100 할당
let height = height ?? 100;
  • 변수에 기본 값을 할당하는 용도로도 사용

Comparison with ||

  • ||는 첫 번째 truthy 값을 반환
  • ??는 첫 번째 정의된(defined) 값을 반환
let x = 0;

alert (x || 100); // 100
alert (x ?? 100); // 0
  • ||는 x=0을 falsy한 값으로 취급하여 null이나 undefined로 처리하고, 100을 반환
  • ??는 정확하게 null이나 undefined일 경우에만 처리하기 때문에 x=0라는 값을 truthy로 판단하여 반환

Precedence

  • 우선 순위는 대부분의 연산자들보다 낮고, =와 ?보다는 높음
    • 복잡한 표현식에서 필요한 경우 () 추가하는 것이 좋음
  • 괄호 없이 &&나 ||와 함께 사용할 수 없음

"JavaScript Fundamentals", by Ilya Kantor, 2007-2022, https://javascript.info/first-steps

profile
괴발개발라이프

0개의 댓글