자바스크립트란 프로그래밍 언어로 스크립트언어에 해당된다 웹을 구성하는 3대 요소인 구조 HTML 디자인 CSS 동력 자바스크립트이다 주로 웹브라우저내에서 주로 사용되며 웹 뿐만 아니라 Node.js 런타임을 통해서 서버쪽으로 사용도 가능하며 다양한 프레임워크를 사용하여 모바일앱, 데스크탑 앱도 만들수있다
변수 let
let value = 1; // 변수
value = 2;
//재할당 가능 재선언 불가능
상수 const
const a = 1 // 상수
//재할당, 재선언 불가능
데이터 타입
let value = 100; // 숫자
let text = "hello"; // 문자열
let good = true //참
let bad = false// 거짓
let some = null // 없다
let any = undefined // 아직 정하지 않음
let value = 1;
// = 또한 대입 연산자
// 상술 연산자 는 덧셈 뺄셈
let a = 1 + 2 - (3 * 4) / 4;
console.log(a);
let b = 1;
b++; // 보여준 다음 계산 하는가
console.log(b++);
++b; // 미리 계산하고 보여주는가
console.log(++b);
//대입 연산사
let c = 1;
c += 3; // 1+3
c -= 3; // 1-3
c *= 3; // 1*3
c /= 3; // 1/3
NOT : !
AND : &&
OR : ||
const a = true;
console.log(!a); // false
const b = true && true;
// 양옆에 둘다 true면 true false면 false
const c = true || false;
//둘중에 하나만이라도 true면 true 다
// 우선 순위
// NOT > AND > OR
const value = !((true && false) || (true && false) || !false);
// false
const a = 1;
const b = 2;
const eq = a === b;
console.log(eq); // false
// == 은 데이터 타입은 비교를 안함
// === 데이터 타입까지 검사함
// 웬만하면 ===를 작성해서 정확하게 하자
const c = "c";
const d = "d";
const notEq = c !== b; // true
const q = 10;
const w = 15;
const e = 15;
console.log(a < b); //true
console.log(b > a); //true
console.log(b >= a); //true
console.log(a <= c); // true
console.log(b < c); // false
// = 사인이 부등호 뒤에 옴
const z = "안녕";
const x = "하세요";
console.log(z + b); // '안녕하세여'
// if 문특정 조건이 만족할 경우 코드를 실행
const a = 1;
if (a + 1 === 2) {
console.log("a+1이 2입니다");
const a = 2;
console.log("if문 안의 a 값은 " + a);
//"if문 밖의 a 값은" + 2
}
console.log("if문 밖의 a 값은" + a);
//"if문 밖의 a 값은" + 1
const q = 10;
if (q > 15) {
console.log("a가 15보다 크다");
} else {
console.log("a가 15보다 크지 않다");
}
if (a === 5) {
console.log("5");
} else if (a === 10) {
console.log("10");
} else {
console.log("5 아니고 10 아니고");
}
// Switch 특정값이 무엇이냐에 따라 다른작업을 한다
const device = "iphone";
switch (device) {
case "iphone":
console.log("아이폰");
break; // 일치하면 멈춘다는 뜻
case "ipad":
console.log("아이패드");
break;
case "galaxy Note":
console.log("갤럭시노트");
break;
default:
// 해당하는 값이 없으면 자동으로 출력
console.log("모르겠디");
}
//break를 안하면 그다음 코드 또한 실행 시킴
//함수는 파라미터라는 input을 받아서 함수내부의 로직을 거쳐 output 결과를 반환함
function add(a, b) {
return a + b;
}
const sum = add(1, 2);
console.log(sum); // 3
function hello(name) {
console.log("hello" + name);
}
hello("이종원"); // 'helle이종원'
//ES6 ECMAScript
//Template Literal
function hihi(name) {
console.log(`hihi ${name}!`);
}
hihi("이종원");
//함수는 return을 적으면 함수가 끝나버림
function getGrade(score) {
if (score === 100) {
return "A+";
} else if (score >= 90) {
return "A";
} else if (score === 89) {
return "b+";
} else if (score >= 80) {
return "b";
} else {
return "C";
}
}
const grade = getGrade(100);
console.log(grade); // A+
const grade2 = getGrade(95);
console.log(grade2); // A
//화살표 함수
const add = (a, b) => {
return a + b;
};
const sum = add(1, 2);
console.log(sum); //3
const hello = (name) => {
console.log(`hello ${name}`);
};
hello("이종원");
//더짧게
const add2 = (a, b) => a + b;
const sum = add2(1, 2);
console.log(sum); //3
//똑같이 작동함:
//객체는 우리가 어떠한 값을 선언할 때 하나에 틀에 여러값을 넣을 수있음
const dogName = "멍멍이";
const dogAge = 2;
const dog = {
name: "멍멍이", //key: value
age: 2,
cute: true,
sample: {
a: 1,
b: 2,
},
};
console.log(dog.name);
console.log(dog.age);
const ironMan = {
name: "토니스타크",
actor: "로버트다우니 주니어",
alias: "아이언맨",
};
const captainAmerica = {
name: "스티븐로저스",
actor: "크리스에반스",
alias: "캡틴아메리카",
};
function print({ alias, name }) {
// const { alias, name } = hero;
const text = `${alias}은 ${name}`;
console.log(text);
}
print(ironMan);
print(captainAmerica);
//객체 안에 함수 넣기
const dog = {
name: "멍멍이",
sound: "멍멍",
say() {
console.log(this.sound);
},
};
dog.say();
//하지만 객체안에 화살표 함수를 작성시 this가 작동을 안함으로 에러가 발생함
const cat = {
name: "야옹이",
sound: "야옹~",
};
cat.say = dog.say;
cat.say();
//Getter 와 Setter
const numbers = {
a: 1,
b: 2,
get sum() {
console.log("sum이 실행됨");
return this.a + this.b;
},
};
// number.a = 5;
// console.log(numbers); // a:5,b:2
console.log(numbers.sum);
numbers.b = 5;
console.log(numbers.sum);
//getter는 특정 값을 조회하려고 할때 특정코드를 실행시키고 연산된 값을 사용함
const dog = {
_name: "멍멍이",
set name(val) {
console.log("이름이 바뀝니다 " + val);
this._name = val;
},
};
console.log(dog._name);
dog.name = "뭉뭉이";
console.log(dog._name);
const arr = [1, 2, 3, 4, 5];
console.log(arr);
const arr2 = [1, "dd", {}, 4];
console.log(arr2[1]); // 1
const obj = [{ name: "멍멍이" }, { name: "야옹이" }];
console.log(obj[0]);
console.log(obj[1].name);
obj.push({ name: "멍뭉이" });
console.log(obj.length);
const arr3 = [1, true, { a: 1 }];
console.log(arr[3]);
//반복문
//특정작업을 반복적으로 사용할때 사용함
//시작 => 조건 => true => 구문 실행
//=> false => 끝
for (let i = 0; i < 10; i++) {
console.log(i); //올라감
}
for (let i = 10; i > 0; i--) {
console.log(i); //내려감
}
const name2 = ["멍멍이", "야옹이", "멍뭉이"];
for (let i = 0; i < name2.length; i++) {
console.log(name2[i]);
}
let i = 0;
while (i < 10) {
console.log(i);
i++;
}
let isFun = false;
while (!isFun) {
console.log(i);
i++;
if (i === 30) {
isFun = true;
}
}
//for of / in
const nums = [10, 20, 30, 40, 50];
for (let num of nums) {
console.log(num);
}
//배열안에 속성을 제어할때 사용함
// 잘 사용안함
const dog = {
name: "멍멍이",
sound: "멍멍",
age: 12,
};
console.log(Object.keys(dog)); // ['name', 'sound', 'age']
console.log(Object.values(dog)); // [ '멍멍이', '멍멍', 12 ]
console.log(Object.entries(dog));
//[ [ 'name', '멍멍이' ], [ 'sound', '멍멍' ], [ 'age', 12 ] ]
for (let key in dog) {
console.log(`${key} : ${dog[key]}`);
}
//name : 멍멍이
//sound : 멍멍
//age : 12
// break continue
for (let i = 0; i < 10; i++) {
if (i === 2) continue;
console.log(i);
if (i === 5) break;
}
// continue 특정 조건이 됬을때 다음 루프를 실행함
// break 특정 조건에 걸리면 반복문이 끝남
// forEach
const hero = ["아이언맨", "캡아", "토르", "닥스"];
function print(arr) {
console.log(arr);
}
hero.forEach(print);
hero.forEach((el) => {
console.log(el);
});
//map , indexOf , findIndex , filter
const arr = [1, 2, 3, 4, 5, 6, 7, 8];
const sq = (n) => {
return n * n;
};
const sq2 = arr.map(sq);
const sq3 = arr.map((el) => {
return el * el;
});
const it = [
{ id: 1, text: "hello" },
{ id: 2, text: "bey" },
];
const it2 = it.map((el) => el.text);
const hero = ["아이언맨", "캡아", "토르", "닥스"];
const index = hero.indexOf("토르");
const todo = [
{ id: 1, text: "공부", done: true },
{ id: 2, text: "식사", done: false },
{ id: 3, text: "hello", done: true },
{ id: 4, text: "취미", done: false },
];
//-1 일치하는게 없다 indexOf를 썻을때
const i = todo.findIndex((todo) => todo.id === 2);
const task = todo.filter((todo) => !todo.done);
console.log(task);
console.log(sq2);
console.log(sq3);
console.log(it2);
console.log(index);
console.log(i);
// splice slice
const num = [10, 20, 30, 40];
const i = num.indexOf(30);
console.log(i);
// const spliced = num.splice(i, 2);
const sliced = num.slice(0, 2);
// console.log(spliced);
// console.log(num);
console.log(sliced);
console.log(num);
// splice 기존의 배열을 건드림 (해당 인덱스 부터, 갯수)짜름
// slice 기존의 배열을 건들지않고 새로운 배열을 만들어사 가져옴 (시작, 마지막 전 까지)
const num = [10, 20, 30, 40];
const val = num.shift(); // 10
const pop2 = num.pop();
// 기존의 값을 건드림
//shift 는 가장 앞에있는 값을 뺌
//pop은 뒤에있는 값을 뺌
num.unShift(5);
num.push(5);
//unshift 가장 앞에있는 값으로 추가함
//push 가장 뒤에있는 값으로 추가함
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr = [1, 2, 3, 4, 5];
console.log(arr.join("/"));
const con = arr1.concat(arr2);
//기존에 값을 건들지 않음
console.log(con);
// reduce
//배열을 값을 연산할때
const num = [1, 2, 3, 4, 5];
const sum = num.reduce((acc, cur, idx, arr) => {
if (idx === arr.length - 1) {
return (acc + cur) / arr.length;
}
return acc + cur;
}, 0);
console.log(sum);
// 0 acc의 초기값
const alph = ["a", "a", "a", "b", "c", "c", "d", "e"];
const count = alph.reduce((acc, cur) => {
if (acc[cur]) {
acc[cur] += 1;
} else {
acc[cur] = 1;
}
return acc;
}, {});
console.log(count);
function countBiggerThanTen(arr) {
return arr.reduce((acc, cur) => {
if (cur <= 10) {
return acc;
} else {
return acc + 1;
}
}, 0);
}
const count = countBiggerThanTen([1, 2, 3, 5, 10, 20, 30, 40, 50, 60]);
console.log(count);
// 프로토타입과 클래스 객체 생성자
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);
}
function Cat(name, sound) {
Animal.call(this, "고양이", name, sound);
}
const dog = new Animal("개", "멍멍이", "멍멍");
const cat = new Animal("고양이", "야옹이", "야옹");
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);
}
}
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 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("네네");
pizza.print();
chicken.print();
// 삼항 연산자
// 기본 구조 condition ? true : false
const arr = [1, 2];
let text = arr.length === 0 ? "배열이 빔" : "배열이 비어있지 않음";
console.log(text);
const con1 = false;
const con2 = false;
const val = con1 ? "와우" : con2 ? "blabla" : "foo";
console.log(val);
//undefined null 0 '' NaN 은 falsy한 값
// 이걸 제외한 나머지는 truthy한 값
console.log(!!undefined);
console.log(!!null);
console.log(!!0);
console.log(!!"");
console.log(!!NaN);
//단축 평가 논리 계산법
const dog = {
name: "멍멍이",
};
function getName(animal) {
return animal && animal.name;
}
console.log(getName(dog));
console.log(true && "hello");
console.log(false && "hello");
// '앞에오는 값이 truthy한 값이면' && '뒤에 값 출력한다'
// 앞에오는 값이 falsy하면 && '앞에 값 출력한다'
// truthy && 뒷 내용
// falsy && 앞 내용
const namelessDog = {
name: "",
};
function getName2(animal) {
const name = animal && animal.name;
return name || "이름이 없는 동물입니다";
}
console.log(getName2(namelessDog));
console.log(false || "hello");
console.log(undefined || "sss");
//앞에오는 값이 falsy하면 || 뒤에값을 출력
//앞에오는 값이 truthy || 앞에 값을 출력
//falsy || 뒷 내용
//truthy || 앞 내용
//함수의 기본 파라미터
function calcul(r = 2) {
return Math.PI * r * r;
}
const area = calcul();
console.log(area);
//그냥 파라미터 = 2 이런식으로 기본값으로 설정해준다
//조건문 더 똒똒하게 쓰끼
function animal(text) {
const ani = ["고양이", "개", "거북이"];
return ani.includes(text);
}
console.log(animal("개"));
console.log(animal("게"));
function getSound(ani) {
const sounds = {
개: "멍멍",
고양이: "야옹",
참새: "짹쩩",
비둘기: "구구",
};
return sounds[ani] || "...?";
}
console.log(getSound("개"));
console.log(getSound("비둘기"));
console.log(getSound("인간"));
function makeSound(animal) {
const tasks = {
게: () => {
console.log("멍멍");
},
고양이() {
console.log("야옹");
},
};
const task = tasks[animal];
if (!tasks[animal]) {
console.log(",,,,??");
return;
}
task();
}
makeSound("개");
makeSound("고양이");
//비구조화 할당
const obj = { a: 1, b: 2 };
const { a, b } = obj;
console.log(a);
console.log(b);
function print({ a, b = 2 }) {
console.log(a);
console.log(b);
}
// print(obj);
const obj2 = { c: 1 };
const { c, d = 2 } = obj2;
console.log(c);
console.log(d);
const ani = {
name: "멍멍",
type: "개",
};
const { name: nickName } = animal;
console.log(nickName);
const arr = [1];
const [one, two = 2] = arr;
const deep = {
state: {
inform: {
name2: "john",
lang: ["ko", "en", "ch"],
},
},
value: 5,
};
const { name2, lang } = deep.state.inform;
const { value } = deep;
const {
state: {
inform: { name, lang },
},
value,
} = deep;
const extracted = {
name2,
lang,
value,
};
console.log(extracted);
// spread rest
const slime = {
name: "슬라임",
};
const cuteSlime = {
...slime,
attribute: "cute",
};
const purpleCuteSlime = {
...cuteSlime,
color: "purple",
};
const greenCuteSlime = {
...purpleCuteSlime,
color: "green",
};
const animals = ["개", "고양이", "참새"];
const anotherAnimals = [...animals, "비둘기"];
// rest 파라미터
function sum(...rest) {
return rest.reduce((acc, cur) => acc + cur, 0);
}
console.log(sum(1, 2, 3, 4, 5, 6));
function max(...rest) {
return rest.reduce((acc, cur) => {
if (acc < cur) {
return (acc = cur);
} else {
return acc;
}
}, 0);
}
const result = max(1, 2, 3, 4, 10, 5, 6, 7);
console.log(result);
//scope
//1,global: 전역 코드의 모든범위에서 사용가능
//2.function: 특정함수에서만 사용가능
//3.block: 블록 내부에서만 사용가능
const value = "hello";
function myFunc() {
console.log("myfunc");
console.log(value);
}
function otherFunc() {
console.log("otherFunc");
const value = "bye";
console.log(value);
}
myFunc();
otherFunc();
console.log("global");
console.log(value);
//hoisting
//가능한 호이스팅은 피해라 왜냐 유지보수 및 코드해석이 어려워짐
//호이스팅을 할려면 함수 표현식으로 써라
myFunc();
function myFunc() {
console.log("hello");
}
//비동기의 처리의 이해
function work(callback) {
setTimeout(() => {
const start = Date.now();
for (let i = 0; i < 100000000; i++) {}
const end = Date.now();
console.log(end - start + "ms");
callback(end - start);
}, 2);
}
console.log("작업시작");
work((ms) => {
console.log("작업끝");
console.log(ms + "ms 걸렸다고함");
});
console.log("다음 작업");
//callback hell
function increasePrint(n, callback) {
setTimeout(() => {
const increased = n + 1;
console.log(increased);
if (callback) {
callback(increased);
}
}, 1000);
}
increasePrint(0, (n) => {
increasePrint(n, (n) => {
increasePrint(n, (n) => {
increasePrint(n, (n) => {
increasePrint(n, (n) => {
console.log("작업 끝");
});
});
});
});
});
//promise
const myPromise = new Promise((res, rej) => {
setTimeout(() => {
rej(new Error());
}, 1000);
});
myPromise
.then((result) => {
console.log(result);
})
.catch((e) => {
console.error(e);
});
function increasePrint(n) {
return new Promise((res, rej) => {
setTimeout(() => {
const value = n + 1;
if (value === 5) {
const error = new Error();
error.name = "valueisFiveError";
rej(error);
return;
}
console.log(value);
res(value);
}, 1000);
});
}
increasePrint(0)
.then(increasePrint)
.then(increasePrint)
.then(increasePrint)
.then(increasePrint)
.then(increasePrint)
.catch((e) => {
console.error(e);
});
//async await
function sleep(ms) {
return new Promise((res) => {
setTimeout(res, ms);
});
}
async function makeError() {
await sleep(1000);
const error = new Error();
throw error;
}
async function process() {
try {
await makeError();
} catch (e) {
console.error(e);
}
}
process().then((value) => {
console.log(value);
});
//promise all
function sleep(ms) {
return new Promise((res) => {
setTimeout(res, ms);
});
}
const getDog = async () => {
await sleep(1000);
return "멍멍이";
};
const getRabbit = async () => {
await sleep(500);
return "토끼";
};
const getTurtle = async () => {
await sleep(3000);
return "거북이";
};
async function process() {
try {
const [dog, rabbit, turtle] = await Promise.all([
getDog(),
getTurtle(),
getRabbit(),
]);
} catch (e) {
console.error(e);
}
}
process();