
수학에서의 변수 = (상황에 따라) 변하는 값
컴공에서의 변수 = 직접 메모리에 할당한 값
명령을 내리기 위한 키워드, 예약어 中 변수를 사용하기 위한 예약어는 var, let
var 권장X > 호이스팅때문에 권장xx
let은 ES6 이후 사용 가능.
let variable = 123
(키워드) (변수명) (값)
변수는 언제든지 값을 바꿀 수 있고, 이 값을 이용하기 위해서는 변수의 이름을 사용하면 됨
변하지 않은 수. (const)
const variable = 126
(키워드) (상수명) (값)
Number 타입
String타입

Boolean 타입
Object 타입

Array 타입
Function 타입
undefined 와 null의 차이
가상머신
자바스크립트는 표현식(Expression)과 문장(Statements)로 이루어져 있다.
Expression 표현식
: 어떠한 결과 값으로 평가되는 식
-> 숫자, 문자열, 논리값 같은 원시 값을 포함하여, 변수, 상수, 함수 호출 등으로 조합할 수 있음
할당 연산자
let x;
x= 10;
x += 5;
x -= 5;
x *= 10;
x /= 10;
x %= 3;
x <<= 4;
x >>= 2;
비교 연산자
const x = 10;
const y = 12;
x == y;
x != y;
x === y;
x !== y;
x > y;
x >= y;
x < y;
x <= y;
"10" == 10 //true
"10" === 10 //false
산술 연산자
const x = 10;
const y = 12;
x + y;
x - y;
x * y;
x / y;
console.log(x / y);
비트 연산자
const x = 10;
const y = 12;
x & y; //AND - 8
x | y; //OR - 14
x ^ y; //XOR - 6
~x; //NOT --11
x << 1;
x >> 1;
논리 연산자
const x = true;
const y = false;
x && y; //AND - false
x || y; //OR - true
!x; //NOT - false
삼항 연산자
조건 ? 참 : 거짓의 형태를 지님const x = 10;
const y = 12;
x > y ? 100 : 200; //200
관계 연산자
const x = {
name: "Lee Sun-Hyoup",
email: "kitter@naver.com",
};
"name" in x; //true
"gender" in x; //false
typeof
const x = 10;
const y = "String";
const z = false;
typeof x; // number
typeof y; // string
typeof z; // boolean
control Flow
: 조건이 맞을 때만 실행되는 문장(Statements) 문법
if
const a = 10;
const b = 20;
if (a < b) {
//참이기 때문에 실행됨
} else {
//무시됨
}
if (a > b) {
//거짓이기 때문에 무시됨
} else if (a === b) {
//마찬가지로 무시됨
} else {
//실행됨
}
-> false 뿐만아니라 undefinded, null, 0, Nan, ''(empty string)도 거짓이 될 수 있으므로 주의
switch
const grade = "B";
switch (grade) {
case "A":
console.log("A grade");
break;
case "B":
console.log("B grade");
break;
case "C":
console.log("C grade");
break;
case "D":
console.log("D grade");
break;
case "F":
console.log("F grade");
break;
default:
console.log("Unknown");
}
: 반복적인 작업을 지시하는 문법
for
for (let i = 0; i< 10; i++) {
console.log(i);
}
while
let x = 0;
while (x < 10) {
x += 1;
console.log(x);
}
do - while
let x = 0;
do {
console.log("Fire");
} while (x > 10)
배열
객체
const arr1 = new Array();
const arr2 = [];
const arr3 = [1, 2, 3, 4, 5];
const arr4 = new Array(5);
const arr5 = new Array(5).fill(5); //fill 함수는 입력받은 파라미터 값으로 모든 요소를 초기화함
const arr6 = Array.from(Array(5), function(v, k) {
return k + 1;
});

배열의 길이
const arr = [1, 2, 3, 4, 5];
console.log(arr.length); //.length는 배열의 길이
arr.length = 3;
console.log(arr);
arr.length = 10;
console.log(arr);

const arr = [1, 2, 3, 4, 5];
console.log(arr.join(', ')); //, 단위로 문자열로 합침
console.log(arr.reverse()); //모든 요소가 거꾸로 뒤집어짐
console.log(arr); //원래 있던 배열에도 영향이 가기 때문에 주의

const arr1 = [1, 2, 3, 4, 5, 6];
const arr2 = [7, 8, 9, 10];
console.log(arr1.concat(arr2)); //두 배열이 합쳐짐

const arr = [1, 2, 3, 4, 5, 6];
arr.push(7); //끝에 요소 추가
console.log(arr);
arr.push(7, 8, 9);
console.log(arr);
arr.pop();
arr.pop();
console.log(arr.pop());
console.log(arr);

const arr = [1, 2, 3, 4, 5, 6];
arr.shift(); //첫번째 요소를 제거
arr.shift();
console.log(arr);
arr.unshift(10); //맨 앞에 요소 추가
console.log(arr);

const arr = [1, 2, 3, 4, 5, 6];
console.log(arr.slice(2, 4)); //중간의 요소 자름
console.log(arr); //원래 배열은 변하지 않음
arr.splice(2, 2);
console.log(arr); //배열이 중간의 요소를 자르면서 변함

for과 for..of


const arr = [1, 2, 3, 4, 5, 6];
console.log(typeof arr); //객체
arr['key'] = "value";
console.log(arr);
console.log(arr.length); //배열의 길이는 내부적으로 관리되어 객체처럼 사용되어도 달라지지 않음

const obj1 = new Object();
const obj2 = {};
const obj3 = {name: "이선협", company: "Cobalt. Inc."};
console.log(obj1);
console.log(obj2);
console.log(obj3);

const obj = {name: "이선협", company: "Cobalt. Inc."};
//추가
obj['email'] = "kciter@naver.com";
console.log(obj);
obj.phone = '01012345678'
console.log(obj);
//삭제
delete obj.phone;
console.log(obj);
//키가 있는지 없는지 확인
console.log("email" in obj);
console.log("phone" in obj);
//키
console.log(Object.keys(obj));
//값
console.log(Object.values(obj));
//for...in로 순회
for(const key in obj) {
console.log(key, obj[key]);
}

스코프
const a = 5; //전역 스코프
{
const b = 3; //지역 스코프
console.log(a, b);
}
console.log(a, b); //error!
const a = 5;
{
//호이스팅되어 변수 선언이 상단으로 올라가버림.
const a = 10;
console.log(a);
}
console.log(a);
클로저
function makeGreeting(name) {
const greeting = "Hello, ";
return function() {
console.log(greeting + name);
};
}
const world = makeGreeting("World!");
const sunhyoup = makeGreeting("Sun-Hyoup");
//그런데 실행 시점에 greeting이 살아있음!
world();
sunhyoup();

은닉화
function Counter() {
let privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment: function() {
changeBy(1);
},
decrement: function() {
changeBy(-1);
},
value: function () {
return privateCounter;
},
};
}
const counter = Counter();
console.log(counter.value());
counter.increment();
counter.increment();
console.log(counter.value());
counter.decrement();
console.log(counter.value());

-> 클로저를 잘 알아야 하는 이유는 유용하게 사용하기 보단 알기 힘든 버그를 수정하기 위해서이다.