JavScript
는 웹 브라우저에서 사용하기 위하여 만들어진 프로그래밍 언어
💡 참고
실행 : cmd + ctrl + n
console.log('Hello JavaScript');
let
: 변수
console
: 상수
선언 : 특정 이름에 특정 값을 설정하는 것
let
은 변수
변수는 바뀔 수 있는 값을 말한다.
한번 값을 선언하고 나서 바꿀 수 있다.
let value = 1;
console.log(value); // 결과 : 1
변수를 선언 할 때는 let
이라는 키워드를 사용한다.
const
은 상수
상수 : 한번 선언하고 값이 바뀌지 않는 값을 의미한다. 값이 고정적이다.
const a = 1;
상수를 선언하고 나면, 값을 바꿀 수 없다.
const a = 1;
a = 2; // a is read-only
💡 참고
더이상var
는 사용하지 말자! (이전 버전에서 사용되던 변수이다. 현재는 사용되고 있지 않다.)
✔️ 숫자(Number)
let value = 1;
✔️ 문자열(String)
let text = 'hello';
let name = '자바스크립트';
✔️ 참/거짓(Boolean)
let good = true;
let loading = false;
✔️ null과 undefined
const friend = null; // null
let criminal;
console.log(criminal); // undefined
null
: 값이 없다. (우리가 없다.)undefined
: 우리가 설정을 하지 않았기 때문에 없는 값이다.
✔️ 논리 연산자
!
: NOT
&&
: AND
||
: OR
연산자 순서 : NOT
-> AND
-> OR
✔️ 비교 연산자
==
: 자료형을 보지 않고 두 값이 일치하는지 비교하는 연산자
===
: 자료형을 보고 두 값이 일치하는지 비교하는 연산자
const a = 1;
const b = `1`;
console.log(a == b); // true
console.log(a === b); // false
!==
: 두 값이 일치하지 않는지 확인할 때 사용
!=
: 타입 검사를 하지 않고 두 값이 일치하지 않는지 확인할 때 사용
funciton add(a, b){
return a + b;
}
const sum = add(1, 2);
console.log(sum); // 3
✔️ 문자열 함수로 합치기
function hello(name){
console.log('Hello, ' + name + '!');
}
hello('velopert'); // 결과 : Hello, velopert
✔️ ES6란 무엇인가?
ES6
: ECMAScript6
, 자바스크립트의 버전을 가리킨다.
function hello(name){
console.log(`Hello, ${name}!`);
}
hello('velopert');
✔️ 화살표 함수
const add = (a, b) => {
return a + b;
};
console.log(add(1, 2));
const add = (a, b) => a + b;
console.log(add(1, 2));
💡 참고
함수가 내부적으로 여러 줄로 구성되어 있는 경우에는 코드 블록으로 만들어야 한다.
function fun(){}
✔️ 객체란?
변수 혹은 상수를 사용하게 될 때 하나의 이름에 여러 종류의 값을 넣을 수 있게 해준다.
ex)
const dog = {
name : '멍멍이',
age : 2
};
console.log(dog.name);
console.log(dog.age);
결과
멍멍이
2
객체를 선언할 때는 {}
문자 안에 원하는 값들을 넣어주면 된다.
키 : 원하는 값
키에 해당하는 부분은 공백이 없어야 한다.
만약 공백이 있을 경우 따옴표로('
) 로 감싸서 문자열로 넣어주면 된다.
const sample = {
'key with space' : true
}
ex) 두 가지의 객체를 생성하여 출력하기
const ironMan = {
name : '토니 스타크',
actor : '로버트 다우니 주니어',
alias : '아이언맨'
};
const captainAmerica = {
name : '스티븐 로저스',
actor : '크리스 에반스',
alias : '캡틴 아메리카'
};
console.log(ironMan);
console.log(captainAmerica);
✔️ 함수에서 객체를 파라미터로 받기
const ironMan = {
name : '토니 스타크',
actor : '로버트 다우니 주니어',
alias : '아이언맨'
};
const captainAmerica = {
name : '스티븐 로저스',
actor : '크리스 에반스',
alias : '캡틴 아메리카'
};
function print(hero){
const text = `${hero.alias}(${hero.name}) 역할을 맡은 배우는 ${hero.actor} 입니다.`;
console.log(text);
}
print(ironMan);
print(captainAmerica);
아이언맨(토니 스타크) 역할을 맡은 배우는 로버트 다우니 주니어 입니다.
캡틴 아메리카(스티븐 로저스) 역할을 맡은 배우는 크리스 에반스 입니다.
✔️ 객체 비구조화 할당
객체 구조 분해
const ironMan = {
name : '토니 스타크',
actor : '로버트 다우니 주니어',
alias : '아이언맨'
};
const captainAmerica = {
name : '스티븐 로저스',
actor : '크리스 에반스',
alias : '캡틴 아메리카'
};
function print(hero){
const { alias, name, actor} = hero;
const text = `${alias}(${name}) 역할을 맡은 배우는 ${actor} 입니다.`;
console.log(text);
}
print(ironMan);
print(captainAmerica);
const { alias, name, actor} = hero;
파라미터 단계에서 객체 비구조화 할당
const ironMan = {
name : '토니 스타크',
actor : '로버트 다우니 주니어',
alias : '아이언맨'
};
const captainAmerica = {
name : '스티븐 로저스',
actor : '크리스 에반스',
alias : '캡틴 아메리카'
};
function print({ alias, name, actor}){
const text = `${alias}(${name}) 역할을 맡은 배우는 ${actor} 입니다.`;
console.log(text);
}
print(ironMan);
print(captainAmerica);
✔️ 객체 안에 함수 넣기
const dog = {
name : '멍멍이',
sound : '멍멍!',
say : function say(){
console.log(this.sound);
}
};
dog.say();
멍멍!
this
: 자신이 속해있는 객체를 가리킨다.
Getter
함수 : 특정 값을 바꿀 때
Setter
함수 : 특정 값을 조회할 때
✔️ Getter
const numbers = {
a : 1,
b : 2,
get sum() {
console.log('sum 함수가 실행된다.');
return this.a + this.b;
}
};
console.log(numbers.sum);
numbers.b = 5;
console.log(numbers.sum);
number.sum
을 조회했을 뿐이지만 함수가 실행되고 그 결과값이 출력되었다.Getter
함수는 특정 값을 조회할 때 설정한 함수로 연산된 값을 반환한다.get
을 함수앞에 붙여준다.
✔️ Setter
const numbers = {
_a : 1,
_b : 2,
sum : 3,
calculate(){
console.log('calculate');
this.sum = this._a + this._b;
},
get a(){
return this._a;
},
get b(){
return this._b;
},
set a(value){
console.log('a가 바뀝니다.');
this._a = value;
this.calculate();
},
set b(value){
console.log('b가 바뀝니다.');
this._b = value;
this.calculate();
}
};
console.log(numbers.sum);
numbers.a = 5;
numbers.b = 7;
numbers.a = 9;
console.log(numbers.sum);
console.log(numbers.sum);
console.log(numbers.sum);
Setter
함수를 설정할 때에는 함수의 앞부분에 set
키워드를 붙인다.numbers.sum
이 조회 될 때마다 덧셈이 이루어졌지만, 이제는 a 혹은 b 값이 바뀔 때마다 sum 값을 연산한다.
배열 : 여러 개의 항목들이 들어있는 리스트와 같다.
const array = [1,2,3,4,5];
배열을 선언할 때에는 []
안에 감싸주면 된다.
✔️ 객체 배열이란?
const object = [{ name : '멍멍이'}, {name : '야옹이'}];
배열을 선언하고 나서, n번째 항목을 조회하고 싶을 때
objects[n];
ex) 객체 배열 입출력 예시
const objects = [{name : '멍멍이'}, {name : '야옹이'}];
console.log(objects);
// [Object, Object]
// 0 : Object
// - name : "멍멍이"
// 1 : Object
// - name : "야옹이"
console.log(objects[0]);
// Object {name : "멍멍이"}
console.log(objects[1]);
// Object {name : "야옹이"}
✔️ 배열에 새 항목 추가하기
배열에 새로운 항목을 추가할 때는 배열이 지니고 있는 내장 함수인 push
함수를 사용한다.
const objects = [{name : '멍멍이'}, {name : '야옹이'}];
objects.push({
name : '멍뭉이'
});
console.log(objects);
[Object, Object, Object]
0 : Object
name : "멍멍이"
1 : Object
name : "야옹이"
2 : Object
name : "멍뭉이"
✔️ 배열의 크기 알아내기
length : 배열의 크기를 알아낼 때 사용한다.
const objects = [{name : '멍멍이'}, {name : '야옹이' }];
console.log(objects.length); // 2
objects.push({
name : '멍뭉이'
});
console.log(objects.length); // 3
for(let i = 0; i < 10; i++){
console.log(i);
}
✔️ for...of
let numbers = [10, 20, 30, 40, 50];
for(let number of numbers){
console.log(number);
}
// 10
// 20
// 30
// 40
// 50
✔️ 객체를 위한 반복문 for...in
const doggy = {
name : '멍멍이',
sound : '멍멍',
age : 2
};
console.log(Object.entires(doggy));
// [Array[2], Array[2], Array[2]]
// 0 : Array[2]
// 0 : "name"
// 1 : "멍멍이"
// 1 : Array[2]
// 0 : "sound"
// 1 : "멍멍"
// 2 : Array[2]
// 0 : "age"
// 1 : 2
console.log(Object.keys(doggy));
// ["name", "sound", "age"]
console.log(Object.values(doggy));
// ["멍멍이", "멍멍", 2]
Object.entires
: [[키, 값], [키, 값]]
형태의 배열로 변환Object.keys.
: [키, 키, 키]
형태의 배열로 변환Object.values
: [값, 값, 값]
형태의 배열로 변환객체가 지니고 있는 값에 대하여 반복을 하고 싶다면 위와 같은 함수를 사용한다.
또는 for...in
구문을 사용해도 된다.
const doggy = {
name : '멍멍이',
sound : '멍멍',
age : 2
};
for(let key in doggy){
console.log(`${key}: ${doggy[key]}`);
}
가장 쉬운 배열 내장함수
✔️ for문과 foreach문
for문
const superheroes = ['아이언맨', '캡틴 아메리카', '토르', '닥터 스트레인지'];
for(let i = 0; i< superheroes.length; i++){
console.log(superheroes[i]);
}
const superheroes = ['아이언맨', '캡틴 아메리카', '토르', '닥터 스트레인지'];
superheros.forEach(hero => {
console.log(hero);
});
forEach
함수의 파라미터로 각 원소에 대하여 처리하고 싶은 코드를 함수로 넣어준다.hero
는 각 원소를 가르키게 된다.
💡 참고
콜백함수 : 함수형태의 파라미터를 전달하는 것 (함수를 등록해주면, forEach가 실행을 해준다.)
map
: 배열 안의 각 원소를 변환할 때 사용되며, 이 과정에서 새로운 배열이 만들어진다.
const array = [1, 2, 3, 4, 5, 6, 7, 8];
배열 안의 모든 숫자를 제곱해서 새로운 배열을 만들고 싶다면?
=> map 함수를 사용하지 않고 이전까지 배운 지식을 활용하면 된다.
const array = [1,2,3,4,5,6,7,8];
const squared = [];
for (let i = 0; i < array.length; i++){
squared.push(array[i] * array[i]);
}
console.log(squared);
forEach
를 쓰면 이와같이 구현할 수도 있다.
const array = [1,2,3,5,6,7,8];
const squared = [];
array.forEach(n => {
squared.push(n * n);
});
console.log(squared);
결과
[1, 4, 9, 16, 25, 36, 49, 64];
위 내용을 map
을 사용할 시 더 짧은 코드를 사용하여 구현할 수 있다.
const array = [1, 2, 3, 4, 5, 6, 7, 8];
const square = n => n * n;
const squared = array.map(square);
console.log(squared);
array.map
함수를 사용할 때 square
를 변화함수로 사용함으로써, 내부의 모든 값에 대하여 제곱을 해서 새로운 배열을 생성했다.
✔️ map 함수는?
변화 함수
: map 함수
의 파라미터, 변화를 주는 함수를 전달해준다.
const squared = array.map(n => n * n);
console.log(squared);
✔️ indexOf
indexOf
: 원하는 항목이 몇번째 원소인지 찾아주는 함수
ex)
const superheroes = ['아이언맨', '캡틴 아메리카', '토르', '닥터 스트레인지'];
const index = superheroes.indexOf('토르');
console.log(index); // 2
✔️ findIndex
배열 안에 있는 값이 숫자, 문자열, 불리언이라면 찾고자하는 항목이 몇번째 원소인지 알아내기 위해 indexOf
를 사용하면 된다.
배열 안에 있는 값이 객체 or 배열이라면 indexOf
로 찾을 수 없다.
const todos = [
{
id : 1,
text : '자바스크립트 입문',
done : true
},
{
id : 2,
text : '함수 배우기',
done : true
},
{
id : 3,
text : '객체와 배열 배우기',
done : true
},
{
id : 4,
text : '배열 내장함수 배우기',
done : false
}
];
findIndex
함수에 검사하고자 하는 조건을 반환하는 함수를 넣어서 찾을 수 있다.
const todos = [
{
id : 1,
text : '자바스크립트 입문',
done : true
},
{
id : 2,
text : '함수 배우기',
done : true
},
{
id : 3,
text : '객체와 배열 배우기',
done : true
},
{
id : 4,
text : '배열 내장함수 배우기',
done : false
}
];
const index = todos.findIndex(todo => todo.id === 3);
console.log(index);
결과 : 2
find
함수 : findIndex
와 비슷하지만, 찾아낸 값이 몇번째인지 알아내는 것이 아닌, 찾아낸 값 자체를 반환한다.
const todos = [
{
id : 1,
text : '자바스크립트 입문',
done : true
},
{
id : 2,
text : '함수 배우기',
done : true
},
{
id : 3,
text : '객체와 배열 배우기',
done : true
},
{
id : 4,
text : '배열 내장함수 배우기',
done : false
}
];
const todo = todos.find(todo => todo.id === 3);
console.log(todo);
결과
{id : 3, text : "객체와 배열 배우기", done : true}
filter
함수 : 배열에서 특정 조건을 만족하는 값들만 따로 추출하여 새로운 배열을 만든다.
ex) todos 배열에서 done값이 false인 항목들만 따로 추출해서 새로운 배열을 만들어보자!
const todos = [
{
id : 1,
text : '자바스크립트 입문',
done : true
},
{
id : 2,
text : '함수 배우기',
done : true
},
{
id : 3,
text : '객체와 배열 배우기',
done : true
},
{
id : 4,
text : '배열 내장함수 배우기',
done : false
}
];
const tasksNotDone todos.filter(todo => todo.done === false);
console.log(tasksNotDone);
결과
[
{
id : 4,
text : '배열 내장 함수 배우기',
done : false
}
]
filter
함수에 넣은 파라미터는 조건을 검사하는 함수를 넣어주며, 이 함수의 파라미터로 각 원소의 값을 받아오게 된다.위에 있는 소스를 이와 같이 변경할 수 있다.
const tasksNotDone = todos.filter(todo => !todo.done);
splice
: 배열에서 특정 항목을 제거할 때 사용한다.
ex) 30을 지우자
const numbers = [10, 20, 30, 40];
const index = numbers.indexOf(30);
numbers.splice(index, 1);
console,log(numbers);
결과
[10, 20, 40]
splice(p1, p2);
slice
: 배열을 잘라낼 때 사용, 기존의 배열은 건들이지 않는다.
const numbers = [10, 20, 30, 40];
const sliced = numbers.slice(0, 2); // 0부터 시작해서 2전까지
console.log(sliced); // [10, 20]
console.log(numbers); // [10, 20, 30, 40]
slice
에는 두 개의 파라미터를 넣게 된다.
shift
: 첫 번째 원소를 배열에서 추출해준다. (추출하는 과정에서 배열에서 해당 원소는 사라진다.)
const numbers = [10, 20, 30, 40];
const value = numbers.shift();
console.log(value);
console.log(numbers);
결과
10
[20, 30, 40]
pop
: push
의 반대로 생각하면 된다. push
는 배열의 맨 마지막에 새 항목을 추가하고, pop
은 맨 마지막 항목을 추출한다.
const numbers = [10, 20, 30, 40];
const value = numbers.pop();
console.log(value);
console.log(numbers);
결과
40
[10, 20, 30]
unshift
: shift의 반대, 배열의 맨 앞에 새 원소를 추가한다.
const numbers = [10, 20, 30, 40];
numbers.unshift(5);
console.log(numbers);
결과
[5, 10, 20, 30, 40]
concat
: 여러개의 배열을 하나의 배열로 합쳐준다.
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const concated = arr1.concat(arr2);
console.log(concated);
결과
[1, 2, 3, 4, 5, 6];
concat
함수는 arr1과 arr2에 변화를 주지 않는다.
join
: 배열 안의 값들을 문자열 형태로 합쳐준다.
const array = [1, 2, 3, 4, 5];
console.log(array.join()); // 1 2 3 4 5
console.log(array.join(' ')); // 1 2 3 4 5
console.log(array.join(', ')); // 1, 2, 3, 4, 5
reduce
: 유용한 내장 함수, 두 개의 파라미터
accumulator
와 current
를 파라미터로 가져와서 결과를 반환하는 콜백함수reduce
함수에서 사용 할 초깃값
💡 참고
accumulator : 누적된 값
const numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce((accumulator, current) => {
console.log({ accumulator, current});
return accumulator + current;
}, 0);
console.log(sum);
코드 실행 결과
accumulator
값이 0인 이유 : 두 번째 파라미터인 초깃값으로 0을 설정했기 때문이다.
✔️ reduce를 사용하여 평균 계산
const numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce((accumulator, current, index, array) => {
if (index === array.length - 1) {
return (accumulator + current) / array.length;
}
return accumulator + current;
}, 0);
console.log(sum);
결과 : 3
index
: 현재 처리하고 있는 항목이 몇 번째인지 가리킨다.array
: 현재 처리하고 있는 배열 자신을 의미한다.ex) 10보다 큰 숫자 갯수 세기
function countBiggerThanTen(numbers) {
/* 구현해보세요 */
let count = 0;
numbers.forEach(n => {
if (n > 10) {
count++;
}
});
return count;
}
const count = countBiggerThanTen([1, 2, 3, 5, 10, 20, 30, 40, 50, 60]);
console.log(count); // 5
export default countBiggerThanTen;
객체 생성자
: 함수를 통해서 새로운 객체를 만들고 그 안에 넣고 싶은 값 혹은 함수들을 구현할 수 있게 해준다.
function Animal(type, name, sound){
this.type = type;
this.name = name;
this.sound = sound;
this.say = function(){
console.log(this.sound);
};
}
const dog = new Animal('개', '멍멍이', '멍멍');
const cat = new Animal('고양이', '야옹이', '야옹');
dog.say();
cat.say();
결과
멍멍
야옹
new
키워드를 앞에 붙여야 한다.
💡 참고
프로토타입이란?
같은 객체 생성자 함수를 사용하는 경우, 특정 함수 또는 값을 재사용 할 수 있다.
프로토타입 객체 생성자 함수 아래에 .prototype.[원하는키] =
코드를 입력하여 설정할 수 있다.
function Animal(type, name, sound){
this.type = type;
this.name = name;
this.sound = sound;
}
Animal.prototype.say = function(){
console.log(this.sound);
};
Animal.prototype.sharedValue = 1;
const dog = new Animal('개', '멍멍이', '멍멍');
const cat = new Animal('고양이', '야옹이', '야옹');
dog.say();
cat.say();
console.log(dog.sharedValue);
console.log(cat.sharedValue);
결과
멍멍
야옹
1
1
function Animal(type, name, sound){
this.type = type;
this.name = name;
this.sound = sound;
}
Animal.prototype.say = function(){
console.log(this.sound);
}
Animal.prototype.sharedValue = 1;
function Dog(name, sound){
Animal.call(this, '개', name, sound);
}
Dog.prototype = Animal.prototype;
function Cat(name, sound){
Amimal.call(this, '고양이', name, sound);
}
Cat.prototype = Animal.prototype;
const dog = new Dog('멍멍이', '멍멍');
const cat = new Cat('야옹이', '야옹');
dog.say();
cat.say();
ES6에서부터 class
라는 문법이 추가되었다.
객체 생성자로 구현했던 코드를 조금 더 명확하고, 깔끔하게 구현할 수 있게 해준다.
상속도 훨씬 쉽게 해줄 수 있다.
class Animal{
constructor(type, name, sound){
this.type = type;
this.name = name;
this.sound = sound;
}
say(){
console.log(this.sound);
}
}
const dog = new Animal('개', '멍멍이', '멍멍');
const cat = new Animal('고양이', '야옹이', '야옹');
dog.say();
cat.say();
결과
멍멍
야옹
prototype
으로 등록이 된다.
class Animal{
constructor(type, name, sound){
this.type = type;
this.name = name;
this.sound = sound;
}
say(){
console.log(this.sound);
}
}
class Dog extends Animal{
constructor(name, sound){
super('개', name, sound);
}
}
class Cat extends Animal{
constructor(name, sound){
super('고양이', name, sound);
}
}
const dog = new Dog('멍멍이', '멍멍');
const cat = new Cat('야옹이', '야옹');
dog.say();
cat.say();
결과
멍멍
야옹
class Animal{
constructor(type, name, sound){
this.type = type;
this.name = name;
this.sound = sound;
}
}
class Dog extends Animal{
constructor(name, sound){
super('개', name, sound);
}
}
class Cat extends Animal{
constructor(name, sound){
super('고양이', name, sound);
}
}
const dog = new Dog('멍멍이', '멍멍');
const dog2 = new Dog('왈왈이', '왈왈');
const cat = new Cat('야옹이', '야옹');
const cat2 = new Cat('냐옹이', '냐옹');
//dog.say();
//dog2.say();
//cat.say();
//cat2.say();
✔️ 보기 좋은 클래스
class Food {
constructor(name) {
this.name = name;
this.brands = [];
}
addBrand(brand) {
this.brands.push(brand)
}
print() {
console.log(`${this.name}을/를 파는 음식점들:`)
console.log(this.brands.join(', '));
}
}
const pizza = new Food('피자');
pizza.addBrand('피자헛');
pizza.addBrand('도미노 피자');
const chicken = new Food('치킨');
chicken.addBrand('굽네치킨');
chicken.addBrand('BBQ');
pizza.print();
chicken.print();