javascript 문서 를 참고했습니다.
ES6 문법이 아니다.
const array = [];
let text = '';
if(array.length === 0){
text = '배열이 비어있습니다.';
}else{
text = '배열이 비어있지 않습니다.';
}
console.log(text);
이와 같이 text값이 달라야 하는 상황이 있을 때
const array = [];
let text = array.length === 0? '배열이 비어있습니다.' : '배열이 비어있지 않습니다.';
console.log(text);
💡 참고
삼항 연산자 :조건 ? true일 때 : false일 때
✔️ 삼항 연산자 중첩
const condition1 = false;
const condition2 = false;
const value = condition1
? '와우!'
: condition2
? 'blabla'
: 'foo';
console.log(value);
if
문을 사용하는 것이 좋다.
Truthy : true, Falsy : false
✔️ 클래스 객체가 undefined
이거나, null
인 상황을 대비
function print(person){
if(!person){
console.log('person이 없다.');
return;
}
console.log(person.name);
}
const person = null;
print(person);
undefined
, null
은 Falsy
한 값이다.Falsy
한 값 앞에 느낌표를 붙여주면 true로 전환한다.
🔔 Falsy 한 값
console.log(!undefined);
console.log(!null);
console.log(!0);
console.log(!'')
;
console.log(!NaN);
-> NaN : Not A Number
const value = {a : 1};
if(value){
console.log('테스트합니다.');
}
null, undefined, 0, '', NaN
중 하나라면 나타나지 않는다.
✔️ getName의 파라미터에 제대로된 객체가 주어지지 않았을 때
const dog = {
name: '멍멍이'
};
function getName(animal){
return animal.name;
}
const name = getName();
console.log(name);
animal
객체가 undefined
이기 때문에, undefined
에서 name
값을 조회할 수 없어서 에러가 발생한다.
✔️ animal 값이 제대로 주어졌을 때, name 조회 그렇지 않다면, undefined를 반환
const dog = {
name : '멍멍이'
};
function getName(animal){
if(animal){
return animal.name;
}
return undefined;
}
const name = getName();
console.log(name);
animal
값이 주어지지 않아도, 에러가 발생하지 않는다.
✔️ 위 코드를 && 연산자로 코드 단축시키기
const dog = {
name : '멍멍이'
};
function getName(animal){
return animal && animal.name;
}
const name = getName();
console.log(name); // undefined
const name2 = getName(dog);
console.log(name2); // 멍멍이
A && B
연산자
ex)
console.log(true && 'hello'); // hello
console.log(false && 'hello'); // false
console.log('hello' && 'bye'); // bye
console.log(null && 'hello'); // null
console.log(undefined && 'hello'); // undefined
console.log('' && 'hello'); // ''
console.log(0 && 'hello'); // 0
console.log(1 && 'hello'); // hello
console.log(1 && 1); // 1
✔️ 위 코드를 || 연산자로 코드 단축시키기
||
연산자 : 어떤 값이 Falsy
하다면 대체로 사용할 값을 지정해줄 때 매우 유용하게 사용할 수 있다.
const namelessDog = {
name : ''
};
function getName(animal){
const name = animal && animal.name;
return name || '이름이 없는 동물입니다.';
}
const name = getName(namelessDog);
console.log(name); // 이름이 없는 동물입니다.
A || B
Truthy
할 경우 결과는 A가 된다.Falsy
하다면 결과는 B가 된다.
✔️ 매개변수 값이 주어지지 않았다면 기본 값을 사용하도록 설정해보자!
function calculateCircleArea(r){
const radius = r || 1; // 값이 0이면 1
return Math.PI * radius * radius;
}
const area = calculateCircleArea();
console.log(area); // 3.1415926~
✔️ 매개변수 값이 주어지지 않았다면, ES6에서는 이렇게
function calculateCircleArea(r = 1){
return Math.PI * r * r;
}
const area = calculateCircleArea();
console.log(area); // 3.14159265 ~
✔️ 함수의 기본 파라미터 문법은 화살표 함수에서도 사용할 수 있다.
function calculateCircleArea = (r = 1) => Math.PI * r * r;
const area = calculateCircleArea();
console.log(area); // 3.14159265 ~
✔️ 특정 값이 여러 값중 하나인지 확인해야 할때
function isAnimal(name){
const animals = ['고양이', '개', '거북이', '너구리'];
return animals,includes(name);
}
console.log(isAnimal('개')); // true
console.log(isAnimal('노트북')); // false
includes
함수를 사용시 여러 값중 하나인지 확인할 수 있다.
💡 참고
좋은 코드란? : 코드가 짧으면서 읽었을 때 어떤 역할을 하는지 잘 이해가 될 수 있어야 좋은 코드이다!
✔️ 값에 따라 다른 결과물을 반환해야할 때
switch case
문을 사용하면 된다.
또 다른 방법으로
function getSound(animal){
const sounds = {
개 : '멍멍!',
고양이 : '야옹~',
참새 : '짹짹',
비둘기 : '구구 구 구'
};
return sounds[animal] || '...?';
}
console.log(getSound('개')); // 멍멍!
console.log(getSound('비둘기')); // 구구 구 구 구
✔️ 값에 따라 다른 결과물을 반환할 때, 실행해야 하는 코드 구문이 다를 때는?
function makeSound(animal){
const tasks = {
개() {
console.log('멍멍');
},
고양이() {
console.log('고양이');
},
비둘기() {
console.log('구구 구 구');
}
};
if(!tasks[animal]){
console.log('...?');
return;
}
tasks[animal]();
}
makeSound('개');
makeSound('비둘기');
✔️ 비구조화 할당 문법을 사용하면?
const object = {a : 1, b : 2};
const {a, b} = object;
console.log(a); // 1
console.log(b); // 2
✔️ 함수의 파라미터에서도 비구조화 할당을 할 수 있다.
const object = { a : 1, b : 2};
function print({ a, b}){
console.log(a);
console.log(b);
}
print(object);
✔️ 비구조화 할당시 기본값 설정
const object = { a : 1};
function print({ a, b = 2}){
console.log(a);
console.log(b);
}
const object = { a : 1};
const { a, b = 2} = object;
console.log(a); // 1
console.log(b); // 2
✔️ 비구조화 할당시 선언 할 값의 이름 바꾸기
const animal = {
name : '멍멍이',
type : '개'
};
const nickname = animal.name;
console.log(nickname); // 멍멍이
=>
const animal = {
name : '멍멍이',
type : '개'
};
const { name : nickname} = animal;
console.log(nickname); // 멍멍이
animal.name
와 nickname
이름이 서로 다르다.:
문자를 사용해서 이름을 바꿔줄 수 있다.name : nickname
=> animal
객체 안에 있는 name
을 nickname
이라고 선언하겠다.
✔️ 배열 비구조화 할당
비구조화 할당은 객체뿐만아니라 배열에서도 가능하다.
const array = [1, 2];
const [one, two] = array;
console.log(one);
console.log(two);
const array = [1];
const [one, two = 2] = array;
console.log(one);
console.log(two);
✔️ 깊은 값 비구조화 할당
객체의 깊숙한 곳에 들어있는 값을 꺼내는 방법
ex) name, languages, value
값들을 밖으로 꺼내주고 싶을 때
const deepObject = {
state: {
information: {
name: 'velopert',
languages: ['korean', 'english', 'chinese']
}
},
value: 5
};
(1) 비구조화 할당 문법을 두 번 사용하는 것
const deepObject = {
state: {
information: {
name: 'velopert',
languages: ['korean', 'english', 'chinese']
}
},
value: 5
};
const { name, languages } = deepObject.state.information;
const { value } = deepObject;
const extracted = {
name,
languages,
value
};
console.log(extracted); // {name: "velopert", languages: Array[3], value: 5}
💡 참고
extracted 객체
를 선언할 때const extracted = { name, languages, value }
==
const extracted = { name: name, languages: languages, value: value }
ES6의 object-shorthand 문법
: 만약에 key 이름으로 선언된 값이 존재한다면, 바로 매칭시켜주는 문법
(2) 한번에 모두 추출하는 방법
const deepObject = {
state: {
information: {
name: 'velopert',
languages: ['korean', 'english', 'chinese']
}
},
value: 5
};
const {
state: {
information: { name, languages }
},
value
} = deepObject;
const extracted = {
name,
languages,
value
};
console.log(extracted);
깊숙히 안에 들어있는 값도 객체에서 바로 추출할 수 있다.
const {
state: {
information: {name, languages}
},
value
} = deepObject;
spread란? : 펼치다, 퍼뜨리다
spread
를 사용하면 객체 혹은 배열을 펼칠 수 있다.
ex)
const slime = {
name: '슬라임'
};
const cuteSlime = {
name: '슬라임',
attribute: 'cute'
};
const purpleCuteSlime = {
name: '슬라임',
attribute: 'cute',
color: 'purple'
};
console.log(slime);
console.log(cuteSlime);
console.log(purpleCuteSlime);
slime
<- cuteSlime
<- purpleCuteSlime
spread
이다.
✔️ spread 문법
const slime = {
name: '슬라임'
};
const cuteSlime = {
...slime,
attribute: 'cute'
};
const purpleCuteSlime = {
...cuteSlime,
color: 'purple'
};
console.log(slime);
console.log(cuteSlime);
console.log(purpleCuteSlime);
...
: spread 연산자
✔️ spread 연산자 배열에서도 사용 가능하다!
const animals = ['개', '고양이', '참새'];
const anotherAnimals = [...animals, '비둘기'];
console.log(animals);
console.log(anotherAnimals);
✔️ spread 연산자 여러 번 사용하기
const numbers = [1, 2, 3, 4, 5];
const spreadNumbers = [...numbers, 1000, ...numbers];
console.log(spreadNumbers); // [1, 2, 3, 4, 5, 1000, 1, 2, 3, 4, 5]
rest
: 객체, 배열, 함수의 파라미터에서 사용이 가능하다.
✔️ 객체에서의 rest
const purpleCuteSlime = {
name: '슬라임',
attribute: 'cute',
color: 'purple'
};
const { color, ...rest } = purpleCuteSlime;
console.log(color);
console.log(rest);
rest
안에는 color
값을 제외한 값이 들어있다.rest
는 객체와 배열에서 사용할 때는 비구조화 할당 문법과 함께 사용된다.rest
라는 키워드를 사용하게 된다. (추출한 값의 이름이 꼭 rest
일 필요는 없다.)const purpleCuteSlime = {
name: '슬라임',
attribute: 'cute',
color: 'purple'
};
const { color, ...cuteSlime } = purpleCuteSlime;
console.log(color);
console.log(cuteSlime);
const purpleCuteSlime = {
name: '슬라임',
attribute: 'cute',
color: 'purple'
};
const { color, ...cuteSlime } = purpleCuteSlime;
console.log(color);
console.log(cuteSlime);
const { attribute, ...slime } = cuteSlime;
console.log(attribute);
console.log(slime);
arrtibute
까지 없앤 새로운 객체
✔️ 배열에서의 rest
const numbers = [0, 1, 2, 3, 4, 5, 6];
const [one, ...rest] = numbers;
console.log(one);
console.log(rest);
결과
0
[1, 2, 3, 4, 5, 6]
💡 참고
one
과...rest
자리를 바꿀 수 없다. 바꾸면 오류남
✔️ 함수 파라미터에서의 rest
function sum(a, b, c, d, e, f, g) {
let sum = 0;
if (a) sum += a;
if (b) sum += b;
if (c) sum += c;
if (d) sum += d;
if (e) sum += e;
if (f) sum += f;
if (g) sum += g;
return sum;
}
const result = sum(1, 2, 3, 4, 5, 6);
console.log(result);
sum(1,2,3,4,5,6)
6개를 넣었주었지만, sum 매개변수 개수는 7개이다.undefined
가 되기 때문에 sum
에 더하는 과정에서 결과로 NaN이 되어버린다.📝 함수의 파라미터가 몇 개가 될 지 모르는 상황일 때
이때, rest
파라미터를 사용하면 매우 유용하다.
function sum(...rest) {
return rest;
}
const result = sum(1, 2, 3, 4, 5, 6);
console.log(result);
결과
[1,2,3,4,5,6]
✔️ 함수 인자와 spread
const myFunction(a) { // 여기서 a 는 파라미터
console.log(a); // 여기서 a 는 인자
}
myFunction('hello world'); // 여기서 'hello world' 는 인자
function sum(...rest) {
return rest.reduce((acc, current) => acc + current, 0);
}
const numbers = [1, 2, 3, 4, 5, 6];
const result = sum(
numbers[0],
numbers[1],
numbers[2],
numbers[3],
numbers[4],
numbers[5]
);
console.log(result);
=>
function sum(...rest) {
return rest.reduce((acc, current) => acc + current, 0);
}
const numbers = [1, 2, 3, 4, 5, 6];
const result = sum(...numbers);
console.log(result);
sum
함수를 사용할 때 인자 부분에서 spread
를 사용
Scope
: 변수 혹은 함수를 선언하게 될 대 해당 변수 또는 함수가 유요한 범위
✔️ Scope 종류 3가지
Global (전역) Scope
: 코드의 모든 범위에서 사용이 가능하다.Function (함수) Scope
: 함수 안에서만 사용이 가능하다.Block (블록) Scope
: if
, for
, switch
등 특정 블록 내부에서만 사용이 가능하다.
const value = 'hello!';
function myFunction() {
console.log('myFunction: ');
console.log(value);
}
function otherFunction() {
console.log('otherFunction: ');
const value = 'bye!';
console.log(value);
}
myFunction();
otherFunction();
console.log('global scope: ');
console.log(value);
value
: Global Scope
로 선언된 값Global Scope
로 선언된 값은 어디에서나 사용이 가능하다.otherFunction
에서 value
라는 값은 Function Scope
로 지정이 되어서 해당 값은 otherFunction
내부에서만 유효한 값이 된다.Global Scope
로 선언된 value
값이 바뀌지 않는다.
결과
const value = 'hello!';
function myFunction() {
const value = 'bye!';
const anotherValue = 'world';
function functionInside() {
console.log('functionInside: ');
console.log(value);
console.log(anotherValue);
}
functionInside();
}
myFunction()
console.log('global scope: ');
console.log(value);
console.log(anotherValue);
functionInside
함수에서는 myFunction
에서 선언한 value
anotherValue
값을 조회할 수 있다.myFunction
밖에서는 antherValue
를 조회할 수 없다.결과
const value = 'hello!';
function myFunction() {
const value = 'bye!';
if (true) {
const value = 'world';
console.log('block scope: ');
console.log(value);
}
console.log('function scope: ');
console.log(value);
}
myFunction();
console.log('global scope: ');
console.log(value);
const
, let
로 선언한 값은 Block Scope
로 선언이 된다.if
문 같은 블록 내에서 새로운 변수/상수를 선언하게 된다면, 해당 블록 내부에서만 사요잉 가능하며, 블록 밖의 범위에서 똑같은 이름을 가진 값이 있다고 해도 영향을 주지 않는다.결과
var value = 'hello!';
function myFunction() {
var value = 'bye!';
if (true) {
var value = 'world';
console.log('block scope: ');
console.log(value);
}
console.log('function scope: ');
console.log(value);
}
myFunction();
console.log('global scope: ');
console.log(value);
var
은 Function Scope
로 선언이 되므로, if
문 블록 내부에서 선언한 value 값이 블록 밖의 value
에도 영향을 미치게 된다.결과
Hoisting
: 아직 선언되지 않은 함수/변수를 "끌어올려서" 사용할 수 있는 자바스크립트의 작동 방식을 의미
myFunction();
function myFunction() {
console.log('hello world!');
}
myFunction
함수를 선언하기 전에, myFunction()
을 호출해주었다.function myFunction() {
console.log('hello world!');
}
myFunction();
Hoisting
이라고 부른다.console.log(number); // 변수 또한 Hoisting이 된다.
✔️ 자바스크립트 엔진 코드 해석할 때
console.log(number);
var number = 2;
=>
위 코드 해석
var number;
console.log(number);
number = 2;
이와 같이 작동한다.
✔️ const
와 let
은 hoisting이 되지만 변수생성과정이 달라서 일시적인 사각지대가 생성되어 초기화전엔 액세스할 수 없다는 레퍼런스 에러를 표시하게 된다.
function fn(){
console.log(a);
let a = 2;
}
fn();
Hoisting
은 자바스크립트 엔진이 갖고 있는 성질 (할 필요는 없으며 방지하는 것이 좋다.)Hoisting
이 발생하는 코드는 이해하기 어렵기 때문에 유지보수도 힘들어지고 의도치 않는 결과물이 나타나기 쉽다.결과
💡 참고
Codesandbox
에서는 자바스크립트가 Babel이라는 도구에 의하여const
와let
이var
로 변환되기 때문에 오류가 발생하지 않는다.
✏️ JavaScript 사용할 때 팁
Hoisting
을 방지하기 위해서, 함수의 경우 꼭 선언 후에 호출을 하도록 주의!var
대신 const
, let
을 위주로 사용하자!ESLint
라는 것을 사용하게 되어 Hoisting
이 발생하는 코드는 에디터상에서 쉽게 발견할 수 있다.