function getResult(number){
let result;
if(number > 5 ) {
result = '👍';
}
else {
result = '🤷♂️'
}
return result;
}
function getResult(number){
result number > 5 ? '👍' : '🤷♂️';
}
Nullish coalescing operator의 기본적인 사용 방법은 아래와 같다.
expr1 ?? expr2
function printMessage(text) {
let message = text;
if(text==null || text==undefined) {
message = "nothing🙄";
}
console.log(message);
}
function printMessage(text) {
const message = text ?? "nothing🙄";
console.log(message);
}
function printMessage(text) {
const message = text ?? "nothing🙄";
console.log(message);
}
printMessage('hello'); // hello
printMessage(undefined); // nothing🙄
printMessage(null); // nothing🙄
null, undefined을 판별하여 맞으면
??
연산자 뒤의 표현식을 반환
function printMessage(text="nothing🙄") {
console.log(text);
}
printMessage('hello'); // hello
printMessage(undefined); // nothing🙄
printMessage(null); // null
default parameter는 undefined인 경우에만 적용된다
Nullish coalescing operator
와는 비슷하지만 살짝 다른 문법이다.
expr1 || expr2
expr1이 falsy한 값이면 expr2가 실행된다
''
or ""
function printMessage(text) {
const message = text || "nothing🙄";
console.log(message);
}
printMessage('hello'); // hello
printMessage(undefined); // nothing🙄
printMessage(null); // nothing🙄
printMessage(0); // nothing🙄
printMessage(''); // nothing🙄
/* 함수인 경우에도 적용 가능 */
const result = getInitialState() || fetchFromServer();
console.log(result); // hello
function getInitialState() {
return null;
}
function fetchFromServer() {
return 'hello';
}
const person = {
name:'Julia',
age:20,
phone:'121212'
}
function displayPerson(person) {
display(person.name);
display(person.age);
display(person.phone);
}
const person = {
name:'Julia',
age:20,
phone:'121212'
}
function displayPerson(person) {
const { name, age, phone } = person;
display(name);
display(age);
display(phone);
}
const person = {name:'hong', age:52};
const detail = {job:'professor', gender:'male'};
person['job'] = detail.job;
person['gender'] = detail.gender;
const person = {name:'hong', age:52};
const detail = {job:'professor', gender:'male'};
// 복사, 합치기와 업데이트가 다 가능
const personInfo = {...person, ...detail, age:20};
let arr = ['apple', 'banana'];
arr.push('tomato');
arr.unshift('grape');
let arr = ['apple', 'banana'];
let arr2 = ['fork', 'beef'];
arr = [...arr, 'tomato'];
arr = [...arr, ...arr2]; // ['apple', 'banana', 'tomato', 'fork', 'beef']
arr = ['grape', ...arr];
// ['grape', 'apple', 'banana', 'tomato', 'fork', 'beef']
const bob = {
name:'jul',
age:20
};
const anna = {
name:'ann',
age:20,
job:{
title:'Web Programmer'
}
}
function displayJobTitle(person) {
if(person.job && person.job.title) {
console.log(person.job.title);
}
}
const bob = {
name:'jul',
age:20
};
const anna = {
name:'ann',
age:20,
job:{
title:'Web Programmer'
}
}
function displayJobTitle(person) {
if(person.job?.title) {
console.log(person.job.title);
}
}