const add = function (a,b) {return a+b;}
const add2 = (a,b) => {return a+b;}
// return이 한 줄인 경우 return과 중괄호 필요 없음.
// 파라미터가 1개일 경우 소괄호도 생략 가능
const score = 85;
let grade = score >= 80? "A" : "B";
논리 연산자를 활용(||, &&, ?., ??)
truthy, falsy
falsy : false, 0, "", null, undefined, NaNconst getUserName = (user) => {
if(!user.name) { // user.name === undefined
return "없음";
}
return user. name;
}
const person = {
age: 30,
};
console.log(getUserName(person)); // "없음"
// user.name이 falsy 값이면 || 다음 내용을 return
const getUserName = (user) => user. name || "없음";
const person = {
age: 30,
};
console.log(getUserName(person)); // "없음"
const loggedIn = true;
const userName = "RingKim1";
// loggedIn이 truthy 값이면 && 다음 내용 실행
loggedIn && console.log(`환영합니다 ${userName}님!`)
const user = {
profile2: {
name: "RingKim,
details: {
age: 31,
location: "제주특별자치도",
},
},
printHello: () => console.log("Hello"),
};
console.log(user.profile.details.age); // cannot read propoerties of undefined
// 값에 접근
console.log(user.profile?.details.age); // undefined
// 함수에 대해
user.printHello1?();
0과 헷갈리지 않도록!let userLocation = null;
// 좌변이 null, undefined인 경우에만 우변을 보여줌
console.log(userLocation ?? "없는 위치");
// userLocation ? userLocation : "없는 위치";
모듈은 재사용 할 수 있는 함수, 객체 또는 원시 값을 의미
// math.js
export const add = (a, b) => a+b;
// app.js
import {add} from `./math.js`
console.log(add(2,3)); // 5
사용 이유
스크립트 파일 간의 종속성과 로딩 순서를 수동으로 관리하지 않기 위해!
코드 캡술화와 충돌방지
효율적인 코드 로딩
고급 모듈기능
// add를 가져와서 a로 쓰겠다.
import {add as a} from `./math.js`
// math.js
export default function multiply (x, y) {
return x * y
}
// app.js
// 가져오는 것이 1개이기 때문에 {} 생략
// M도 아무 이름으로 지을 수 있음
import M from `./math.js`
import * as MathFunctions from `./math.js`
와 아직 자바스크립트도 모르겠는데 리액트 하려니 머리가 어지럽다...
오늘의 점심 : 바나나 + (닭가슴살)볶음밥