숫자형
// 거듭제곱
console.log(2 ** 3); // 8
// 덧셈
console.log(2 + 9); // 11
// 뺄셈
console.log(4 - 7); // -3
// 곱셈
console.log(2 * 5 * 4); // 40
// 나눗셈
console.log(4 / 3); // 1.33333
// 사칙연산 우선순위대로 연산이 됨
console.log(2 + 3 * 2);
console.log((3 + 4) * 8);
문자열
문자열은 양끝을 같은 따옴표로 감싸야 함.
세미콜론(;)은 출력되지 않음.
// 문자열
// console.log('I'm Iron man'); // → 오류남
/* 해결방안
큰따옴표로 문장 전체를 감싼다 */
console.log("'I'm Iron man'");
// 문자열 안에 작은따옴표와 큰따옴표가 모두 있어야 한다면?
console.log("He said \"I'm Iron man\"");
console.log('He said "I\'m Iron man"');
console.log("He said \"I\'m Iron man\"");
console.log('He said \"I\'m Iron man\"');
/*
가독성을 높이기 위해서
양끝의 따옴표를 백틱으로 바꿈.
*/
console.log(`He said "I'm Iron man"`);
// 문자열 덧셈 : 문자열을 연결하는 것
console.log('Hello' + 'Codeit')
// HelloCodeit이 출력됨.
console.log('3' + "25");
// 325가 출력됨.
// 본인이 더하는게 문자인지, 숫자인지 확인하자!
문자열을 따옴표("), 또는 홑따옴표(')로 묶어 나타낼 수 있음.
출력하려는 문자열에 따옴표가 포함된 경우
다른 종류의 따옴표를 사용하거나, 이스케이프 문자를 사용하여 문자열 내에서 따옴표를 이스케이프 처리해야 함.
문자열 덧셈은 문자열을 그대로 연결하는 것임.
본인이 더하는 것이 문자인지, 숫자인지 확인하자!
console.log("한국 영화 역사상 아카데미상을 받은 것은 '기생충'이 처음이다.")
console.log("아리스토텔레스는 \"인간은 사회적 동물이다.\"라고 말했다.")
// 백슬래시는 따옴표 앞에 붙인다
console.log(`영화 '베테랑'에서 "어이가 없네~"라는 대사가 유명했다.`)
console.log("영화 '베테랑'에서 \"어이가 없네~\"라는 대사가 유명했다.")
불 대수
불대수 : 일상적인 논리를 수학적으로 표현한 것
일반 수학의 값 = 숫자 |
-1, -2, 3.14, 1, 2, 3 |
불대수의 값 = 진리값 |
True, False and, or, not |
명제
대한민국의 수도는 서울이다. → 참인 명제
2는 1보다 작다 → 거짓인 명제
한국의 수도는 어디입니까? → 명제가 아님 (질문)
짜장면보다 짬뽕이 맛있다. → 명제가 아님 (명확하게 참과 거짓을 판단할 수 없음)
AND 연산
A와 B가 모두 참일 때만 A AND B가 참
A |
B |
A AND B |
True |
True |
True |
True |
False |
False |
False |
True |
False |
False |
False |
False |
대한민국의 수도는 서울이다. (True) AND 2는 1보다 크다. (True)
대한민국의 수도는 서울이고, 2는 1보다 크다. (True)
대한민국의 수도는 서울이다. (True) AND 2는 1보다 작다. (False)
대한민국의 수도는 서울이고, 2는 1보다 작다. (False)
OR 연산
A와 B 중 하나라도 참이면 A OR B는 참
A |
B |
A OR B |
True |
True |
True |
True |
False |
Ture |
False |
True |
True |
False |
False |
False |
대한민국의 수도는 제주도다. (False) OR 대한민국의 수도는 서울이다. (True)
대한민국의 수도는 제주도거나 서울이다. (True)
대한민국의 수도는 제주도다. (False) OR 대한민국의 수도는 부산이다. (False)
대한민국의 수도는 제주도거나 서울이다. (False)
NOT 연산
A |
NOT A |
True |
False |
False |
True |
NOT 대한민국의 수도는 서울이다. (True)
대한민국의 수도는 서울이 아니다. (False)
NOT 2는 1보다 작다. (False)
2는 1보다 작지 않다. (True)
불린형
// 불린 (Boolean)
console.log(2 > 1);
console.log(2 < 1);
console.log(3 >= 2);
console.log(3 <= 3);
// console.log(3 => 3); --> 오류 발생
console.log(3 === 2);
console.log(3 !== 3);
// 주의할 점 : 등호를 부등호 뒤에 써야 됨.
console.log('Codeit' === 'Codeit')
console.log("Codeit" !== "Codeeat")
// Shift + 7 ==> & (AND) 연산자
console.log(true && true);
console.log(true && false);
console.log(false && true);
console.log(false && false);
// Shift + \ ==> | (OR) 연산자
console.log(true || true);
console.log(true || false);
console.log(false || true);
console.log(false || false);
// Shift + 1 ==> ! (NOT) 연산자
console.log(!true);
// 연산자를 중첩해서 사용
console.log(!!true); //true
console.log(!!false); //false
// 불린 (Boolean)
console.log(2 < 1 && 'Codeit' !== 'Codeit');
console.log(7 !== 7 || 4 < 3); // false || false --> false
let x = 3;
console.log(x > 4 || !(x > 2)); // false || false ---> false
let x = 3;
console.log(x > 4 || !(x > 2));
console.log(false || !true); // false || false
console.log(false);
typeof 연산자
// typeof 연산자
console.log(typeof 101); // number
console.log(typeof 'codeit'); // string
console.log(typeof true); // boolean
console.log(typeof "true"); // string
console.log(typeof 1); // number
console.log(typeof 1.0); // number
console.log(typeof '1'); // string
console.log(typeof "1"); // string
console.log(typeof `1`); // string
// 변수에서 활용
let name = 'codeit';
function sayHello() {
console.log('Hello');
};
console.log(typeof name); // string
console.log(typeof sayHello); // function
// 함수는 function이라고 출력됨.
// 연산자를 넣어보자
console.log(typeof 'Hello' + 'Codeit'); // stringCodeit
// 1) typeof 'Hello'
// 2) string + 'Codeit'
console.log(typeof 8 - 3); // NaN (Not a number) -> 숫자가 아닌 값
// 1) typeof 8
// 2) number + - 3 (문자열과 숫자값을 연산하려고 해서!)
// 해결방법 : 괄호를 씌워주어서 연산자에 우선순위를 부여하면 됨.
console.log(typeof ('Hello' + 'Codeit')); // string
console.log(typeof (8 - 3)); // number
연산자 우선순위
ECMAScript 사양에서 정의된 자바스크립트 연산자 우선순위
21 (grouping) ( ... )
20 new (with argument list) new ...
19 Member Access ... . ... ... [ ... ]
... ?. ... ... ?[ ... ]
new ... . ... new ... [ ... ]
new ... ?. ... new ... ?[ ... ]
18 Function Call ... ( ... )
... optional chaining ... ( ... )
... optional chaining ... [ ... ] ( ... )
... ?. ... ( ... )
... ?. ... [ ... ] ( ... )
... new ... ( ... )
... new ... [ ... ] ( ... )
17 Postfix Increment ... ++
... --
16 Logical NOT ! ...
delete ...
typeof ...
void ...
await ...
15 Exponentiation ... ** ...
14 Multiplication ... * ...
... / ...
... % ...
13 Addition ... + ...
... - ...
12 Bitwise Shift ... << ...
... >> ...
... >>> ...
11 Relational ... < ...
... <= ...
... > ...
... >= ...
... instanceof ...
... in ...
10 Equality ... == ...
... != ...
... === ...
... !== ...
9 Bitwise AND ... & ...
8 Bitwise XOR ... ^ ...
7 Bitwise OR ... | ...
6 Logical AND ... && ...
5 Logical OR ... || ...
4 Optional Chaining ... ?. ...
3 Conditional ... ? ... : ...
2 Assignment ... = ...
... += ...
... -= ...
... *= ...
... /= ...
... %= ...
... <<= ...
... >>= ...
... >>>= ...
... &= ...
... ^= ...
... |= ...
1 Comma ... , ...
연산자의 우선순위는 위에서 아래로 내려갈수록 높아지고, 같은 수준의 연산자일 경우 왼쪽에서 오른쪽으로 계산됨.
예를 들어, 곱셈(*)과 나눗셈(/) 연산자는 같은 수준(15)이므로, 곱셈 연산자가 나눗셈 연산자보다 먼저 계산됨.
형 변환
자바스크립트에서 더하기 기호는 숫자를 더하는 것보다 문자를 연결하는 기능이 더 많다.
더하기로 연결할 때 순서에 상관없이 어느 한 쪽이라도 문자열이 있다면 양쪽 모두 문자열로 바꾼다음 문자열 연산으로 동작함.
// 형 변환(Type Conversion)
console.log('10' + '5'); // 105
console.log(10 + 5); // 15
// 형변환하고 싶으면 대문자로 된 함수 사용
// String, Number, Boolean
console.log(Number('10') + Number('5')); // 숫자 15
console.log(String(10) + String(5)); // 문자 105
// 숫자 -> 문자
let x = 123;
console.log(x); // 123 (숫자)
console.log(String(x)); // 123 (문자)
console.log(typeof x); // number
console.log(typeof String(x)); // string
console.log('');
// 불린 -> 문자
let y = true;
console.log(y); // true
console.log(String(y)); // true
console.log(typeof y); // boolean
console.log(typeof String(y)); // string
// 문자 -> 숫자
let A = '문자';
console.log(A); // 문자
console.log(Number(A)); // NaN
console.log(typeof A); // string
console.log(typeof Number(A)); // number
console.log('');
// 불린 -> 숫자
let B = true;
console.log(B); // true
console.log(Number(B)); // 1
console.log(typeof B); // boolean
console.log(typeof Number(B)); // number
let C = true;
console.log(C); // true
console.log(Number(C)); // 1
// 문자 -> 불린
let D = '문자';
console.log(D); // 문자
console.log(Boolean(D)); // true
console.log(typeof D); // string
console.log(typeof Boolean(D)); // boolean
console.log('');
// 숫자 -> 불린
let E = 123;
console.log(E); // 123
console.log(Boolean(E)); // true
console.log(typeof E); // number
console.log(typeof Boolean(E)); // boolean
// 형변환했을 때 false값이 나오는 문자
// '' , 0 , NaN ----> falsy
console.log(Boolean("false")) // true
console.log(Boolean(false)) // false
console.log(Boolean(6 % 2)) // false
console.log(Boolean(NaN) || Boolean('0'))// true
// false || true
console.log(Boolean(0)) // false
console.log(Boolean('0')) // true
console.log(Boolean(typeof false)) // true
// 산술 연산(+, -, *, /, %, **)
console.log(4 + '2'); // 42
console.log(4 + 2); // 6
console.log(4 - true); // 3
console.log(4 * false); // 0
console.log(4 / '2'); // 2
console.log('4' ** true); // 4
console.log(4 % 'two'); // NaN
// 'two'는 형변환하면 NaN
// NaN은 어떤 것과 연산해도 결과값이 NaN으로 나옴.
// ★★★ 관계 비교 연산(<, <=, >, >=) ★★★
console.log( 2 < '3'); // true
// 문자열 3이 숫자 3으로 형변환
console.log( 2 > true); // true
// Boolean true가 1로 형변환
console.log( '2' <= false); // false
// 문자열 2가 숫자 2로 형변환
console.log('two' >= 1); // false
// 문자열 2가 NaN으로 형변환
/*
'two'는 NaN으로 형변환되나,
관계 비교 연산에서는 결과값을 true or false로 내야되기 때문에
비교가 불가능한 경우에도 false가 나옴
*/
// ★★★ 같음 비교 연산 (===, !==, ==, !=) ★★★
// 일치, 불일치 (!==) [자료형과 값 모두 같아야]
console.log(1 === '1'); // false
console.log(1 === true); // false
// 동등, 부등 (!=) [값만 같으면 됨]
console.log(1 == '1'); // true
console.log(1 == true); // true
// 문자 1과 불린 true가 1로 형변환됨.
// 템플릿 문자열 (template strings)
// template: 일정한 틀, 형식
let year = 2023;
let month = 4;
let day = 28;
console.log('생년월일은' + year + '년' + month + '월' + day + '일')
// 코드 한 줄이 너무 길어지고, 변수 구간에 매번 더하기를 넣어줘야 됨.
console.log(`생년월일은 2023년 4월 28일 입니다.`);
console.log(`생년월일은 ${year}년 ${month}월 ${day}일 입니다.`);
let myNumber = 3;
function getTwice(x) {
return x = 2;
}
console.log(`${myNumber}`의 두 배는 ${getTwice(myNumber)입니다.});
// null과 undefined
null = 의도적으로 표현할 때 사용하는 값
undefined = 코드를 실행하면서 값이 없다는 것을 확인하는 값
let codeit;
console.log(codeit);
// undefined - 선언만 하고 아무런 값을 지정하지 않음
let codeeat;
codeeat = undefined;
console.log(undefined);
// undefined
// 코드를 실행할 때 문제가 되지 않지만 굳이 사용할 필요가 없음
let codeeat;
codeeat = null;
console.log(codeeat);
// null - 값이 없음을 의도적으로 표현한 것
console.log(null == undefined); // true
console.log(null === undefined); // false
let cup;
console.log(cup); // undefined
cup = '물';
console.log(cup); // 물
cup = null;
console.log(cup); // null