알고 있으면 유용한 자바스크립트 문법

LeeKyoungChang·2022년 10월 15일
0
post-thumbnail

javascript 문서 를 참고했습니다.

 

📚 1. 삼항 연산자

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문을 사용하는 것이 좋다.

 

 

📚 2. Truthy and Falsy

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, nullFalsy 한 값이다.
  • 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('테스트합니다.');
}
  • value가 null, undefined, 0, '', NaN 중 하나라면 나타나지 않는다.

 

 

📚 3. 단축 평가 (short-circuit evaluation) 논리 계산법

✔️ 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 연산자
    • A가 Truthy 한 값일 때, B가 결과값이 된다.
    • A가 Falsy 한 값이라면 결과가 A가 된다.

 

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
    • 만약 A가 Truthy 할 경우 결과는 A가 된다.
    • A가 Falsy 하다면 결과는 B가 된다.

 

 

📚 4. 함수의 기본 파라미터

✔️ 매개변수 값이 주어지지 않았다면 기본 값을 사용하도록 설정해보자!

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 ~

 

 

📚 5. 조건문 더 스마트하게 쓰기

✔️ 특정 값이 여러 값중 하나인지 확인해야 할때

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('비둘기');
  • 객체에 함수를 넣으면 된다!

 

 

📚 6. 비구조화 할당 (구조분해) 문법

✔️ 비구조화 할당 문법을 사용하면?

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
  • b 값에 기본 값을 주고 싶을 때 이와 같이 사용

 

✔️ 비구조화 할당시 선언 할 값의 이름 바꾸기

const animal = {
	name : '멍멍이',
	type : '개'
};

const nickname = animal.name;
console.log(nickname); // 멍멍이

=>

const animal = {
	name : '멍멍이',
	type : '개'
};

const { name : nickname} = animal;
console.log(nickname); // 멍멍이
  • animal.namenickname 이름이 서로 다르다.
  • 이러한 상황에서는 : 문자를 사용해서 이름을 바꿔줄 수 있다.
  • name : nickname => animal 객체 안에 있는 namenickname이라고 선언하겠다.

 

✔️ 배열 비구조화 할당

비구조화 할당은 객체뿐만아니라 배열에서도 가능하다.

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;

 

 

📚 7. spread와 rest

📖 A. spread

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);
  • 기존의 animals는 건드리지 않으며, 새로운 anotherAnimals 배열에 animals가 가지고 있는 내용을 모두 집어넣고, '비둘기' 라는 항목을 추가적으로 넣었다.

 

✔️ 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]
  • 배열에서 여러 번 사용하기

 

📖 B. rest

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);
스크린샷 2022-10-15 오후 5 11 01
  • 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]
  • 배열 비구조화 할당을 통하여 원하는 값을 밖으로 꺼내고, 나머지 값을 rest 안에 넣었다.

💡 참고
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개이다.
  • 그러므로, g값이 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를 사용

 

 

📚 8. 자바스크립트의 Scope에 대한 이해

Scope : 변수 혹은 함수를 선언하게 될 대 해당 변수 또는 함수가 유요한 범위

✔️ Scope 종류 3가지

  • Global (전역) Scope : 코드의 모든 범위에서 사용이 가능하다.
  • Function (함수) Scope : 함수 안에서만 사용이 가능하다.
  • Block (블록) Scope : if, for, switch 등 특정 블록 내부에서만 사용이 가능하다.

 

📖 A. Scope란?

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 값이 바뀌지 않는다.

 

결과

스크린샷 2022-10-15 오후 5 41 27

 

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를 조회할 수 없다.

결과

스크린샷 2022-10-15 오후 5 45 13

 

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문 같은 블록 내에서 새로운 변수/상수를 선언하게 된다면, 해당 블록 내부에서만 사요잉 가능하며, 블록 밖의 범위에서 똑같은 이름을 가진 값이 있다고 해도 영향을 주지 않는다.

결과

스크린샷 2022-10-15 오후 5 49 20

 

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);
  • varFunction Scope로 선언이 되므로, if문 블록 내부에서 선언한 value 값이 블록 밖의 value에도 영향을 미치게 된다.

결과

스크린샷 2022-10-15 오후 5 52 30

 

 

📖 B. Hoisting

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;

이와 같이 작동한다.

 

✔️ constlet은 hoisting이 되지만 변수생성과정이 달라서 일시적인 사각지대가 생성되어 초기화전엔 액세스할 수 없다는 레퍼런스 에러를 표시하게 된다.

function fn(){
	console.log(a);
	let a = 2;
}
fn();
  • Hoisting은 자바스크립트 엔진이 갖고 있는 성질 (할 필요는 없으며 방지하는 것이 좋다.)
    • Hoisting이 발생하는 코드는 이해하기 어렵기 때문에 유지보수도 힘들어지고 의도치 않는 결과물이 나타나기 쉽다.

결과

스크린샷 2022-10-15 오후 6 04 42

💡 참고
Codesandbox에서는 자바스크립트가 Babel이라는 도구에 의하여 constletvar로 변환되기 때문에 오류가 발생하지 않는다.

 

✏️ JavaScript 사용할 때 팁

  • Hoisting을 방지하기 위해서, 함수의 경우 꼭 선언 후에 호출을 하도록 주의!
  • var 대신 const, let을 위주로 사용하자!
  • 자바스크립트 개발에 본격적으로 하게 될 때에는 ESLint라는 것을 사용하게 되어 Hoisting이 발생하는 코드는 에디터상에서 쉽게 발견할 수 있다.

 

 

profile
"야, (오류 만났어?) 너두 (해결) 할 수 있어"

0개의 댓글

관련 채용 정보