let age = 30;
console.log(age); // 30
var age = 30;
var age = 20;
console.log(age) // 20
var는 변수를 같은 이름으로 두번 선언했지만 에러가 발생하지 않습니다.
let age = 30;
let age = 20; // 에러 발생
let 변수를 같은 이름으로 두번 선언하면 에러가 발생합니다.
const는 상수입니다. 상수는 변경이 불가능합니다.
const age = 30;
age = 20; // 에러 발생
let age = 30;
let time = 2.1;
let inf = Infinity;
let minf = -Infinity;
let nan = NaN;
let name = "jay";
let name2 = "jay";
let name3 = `jay ${name2}`;
console.log(name3); // jay jay
let result = true;
let a;
console.log(undefined); // undefined
let a = null;
console.log(a); // null
let a = 1;
let b = "2";
console.log(a * b); // 2
console.log(a + b); // 12
number과 string을 연산하게 되면 묵시적 형변환되어 적용되게 된다. a + b가 3이 되게 하려면 b를 형변봔 후 계산을 하면 됩니다.
console.log(a + parseInt(b)); // 3
function getArea(width, height) {
return width * height;
}
let area = getArea(10, 20);
console.log(area);
let a;
a = a ?? 10;
console.log(a); // 10
a가 null 이거나 undefined이면 10을 대입하는 코드.
let hello = function () {
return "hi";
};
console.log(hello);
console.log(hello());
이렇게 무명함수를 변수에 담아서 사용하는 것을 함수 표현식이라고 합니다.
console.log(hi()); // hi
let hello = function () {
return "hello";
};
function hi() {
return "hi";
}
위의 코드처럼 function hi를 아래 선언하고 위에서 호출을 했지만 정상적으로 콘솔에 값이 찍힙니다. 이것을 js의 호이스팅이라고 합니다.
함수 선언식으로 만들어진 함수들은 프로그램 실행 전에 코드의 최상단으로 끌어올려져서 실행이 됩니다.
console.log(hi()); // hi
console.log(hello()); // TypeError : hello is not a function
let hello = function () {
return "hello";
};
function hi() {
return "hi";
}
함수 표현식은 호이스팅이 이루어지지 않습니다. 그렇기 때문에 선언 후에 사용을 해야 합니다.
let hi = () => "hi";
console.log(hi()); // hi
간단하게 다른 함수에 매개변수로 함수로 넘겨준 것 입니다.
function checkHungry(lunch, hungryCallback, fullCallback) {
if (lunch === null || undefined) {
// 점심 안먹었을 때 동작
hungryCallback();
} else {
// 점심 먹었을 때 동작
fullCallback();
}
}
function eating() {
console.log("eat");
}
function running() {
console.log("fun");
}
function studying() {
console.log("study");
}
checkHungry(null, eating, studying); // eat
이렇게 함수의 매개변수로 다른 함수를 넘겨줄 수 있습니다.
객체 생성 방법
let person1 = new Object(); // 생성자 방식
let person2 = {}; // 객체 리터럴
let person = {
key1 : 'value',
key2 : 'value2'
} // 객체 프로퍼티
console.log(person);
value에 다양한 값을 넣어보도록 하겠습니다.
let person = {
key1: "value",
key2: "value2",
key3: true,
key4: [1, 2],
key5: function () {}
}; // 객체 프로퍼티
console.log(person);
프로퍼티 value에는 어떤 자료형이 들어가도 다 가능합니다.
value값 꺼내는 방법
console.log(person.key1);
console.log(person["key1"]);
점표기법을 사용하는게 편하지만 괄호표기법을 사용해야할 경우가 있습니다.
function getPropertyValue(key) {
return person[key];
}
이런 경우 동적인 파라미터를 받아서 value값을 꺼낼 때 괄호표기법으로 쉽게 value를 가져올 수 있습니다.
let person = {
name: "jay",
age: 90
};
person.location = "한국";
person["hand"] = "right";
console.log(person);
let person = {
name: "jay",
age: 90
};
delete person.age;
delete person["name"];
console.log(person); // {}
실제로 메모리에서 name, age는 지워지지 않지만 객체와 끊어지게 만드는 것입니다.
그래서 보통 객체의 key value를 삭제할 때는 아래 방법을 사용합니다.
person.age = null;
person.name = null;
이번에는 객체 안에 없는 key 값을 사용해 보도록 하겠습니다.
let person = {
name: "jay",
age: 90
};
console.log(person.gender); // undefined
에러가 발생하지 않고 undefined가 출력되는 것을 볼 수 있습니다. key값이 없으면 객체에 접근을 못하게 해보겠습니다.
let person = {
name: "jay",
age: 90
};
function getValueInObject(object, key) {
if (key in object) {
return object[key];
} else {
throw new Error("존재하지 않는 키 입니다.");
}
}
console.log(getValueInObject(person, "age"));
console.log(getValueInObject(person, "test"));
key in object 문법을 사용해서 존재하면 값을 return 하고 존재하지 않으면 error를 발생시켜 보았습니다.
배열은 순서있는 요소들의 집합 입니다.
let arr1 = new Array();
let arr2 = []; // 배열 리터럴
let arr = [1, "2", null, 4, function () {}];
console.log(arr);
array 역시 다양한 자료형을 담을 수 있습니다.
let arr = [1, 2, 3, 4, 5]; // 배열 리터럴
console.log(arr[0]); // 1
console.log(arr[1]); // 2
let arr = [1, 2, 3, 4, 5]; // 배열 리터럴
arr.push(6);
console.log(arr); // (6) [1, 2, 3, 4, 5, 6]
keys 배열로 return
let person = {
name: "jay",
age: 90,
hand: "right"
};
const personKeys = Object.keys(person); // keys 배열로 return
console.log(personKeys);
console.log(typeof personKeys);
해당 게시글은 인프런 강의
"한입 크기로 잘라 먹는 리액트(React.js) : 기초부터 실전까지(이정환)"
를 정리한 내용입니다. 쉽게 잘 설명해주시니 여러분도 강의를 듣는 것을 추천드립니다.