javascript-모던 자바스크립트

JM·2022년 3월 28일
0
post-thumbnail

문장(statements)

어떤 동작이 일어나도록 작성된 최소한의 코드 덩어리
선언문, 조건문, 반복문 이렇게 끝에 문이라고 붙는 이유가 동작을 수행하는 문장이기 때문이다.

let x;
x = 3;

if (x < 5) {
	console.log('x는 5보다 작습니다.');
}

표현식(expressions)

하나의 값이 되는 모든 코드를 가리킨다.
표현식은 문장의 일부로 쓰이지만, 그 자체로 문장일 수도 있다.

표현식인 문장 vs 표현식이 아닌 문장

구별하는 간단한 방법은 문장을 변수에 할당하거나, 어떤 함수의 아규먼트로 전달해 보는 것이다.
조건문과 반복문은 Error가 발생한다.
조건문이나 반복문은 값으로 평가 되지 않고 오로지 문장으로만 평가해보자.

조건 연산자

삼항 연산자 (Ternary operator)

조건 ? 참일 때 표현식 : 거짓일 때 표현식;

const cut_off = 80;

function passChecker(score){
	return score > cut_off ? '합격' : '불합격';
}

console.log(passChecker(90));

Spread 구문

const startNumbers = [1, 2, 3];
const nextNumbers = [4, 5, 6];

const start_next_Numbers = [...startNumbers, ... nextNumbers];

// slice를 사용해서 배열을 복사해야한다.
const newNumbers = numbers.slice();

// 이렇게 스프레드로 복사할 수 있다.
const newNumbers = [...numbers];

console.log(numbers); 	// [1, 2, 3]
console.log(...numbers);	// 1, 2, 3
console.log(start_next_Numbers); // [1, 2, 3, 4, 5, 6];

모던한 프로퍼티 표기법

const title = 'Codeit';
const birth = 2017;
const job = '프로그래밍 강사';

// 객체 생성 방법 1
const user = {
  title: title,
  birth: birth,
  job: job
}
// 객체 방법 2
const user = {
  title,
  birth,
  job
}

function getFullName(){
	return `${this.title} ${this.birth} ${this.job}`
}

// 객체 방법 3
const user = {
  title,
  birth,
  job,
  getFullName
}
// 계산된 속성명
const propertyName = 'birth';
const getJob = () => 'job';

const codeit = {
	['topic' + 'Name']: 'Modern JavaScript',
	[propertyName]: 2017,
	[getJob()]: '프로그래밍 강사'
}

옵셔널 체이닝

const user1 = {
  name: 'Captain',
  cat: {
  	name: 'Crew',
    breed: 'British Shorthair'
  }

}

function printCatName(user) {
  console.log(user.cat?.name); // 참이면 name 값을 거짓이면 undefined 출력
}

// 예외 처리
function printCatName(user){
	console.log(user.cat?.name ?? '함께 지내는 고양이가 없습니다.');
}

const user2 = {
	name: 'Young';
}

console.log(user2) // 함께 지내는 고양이가 없습니다.

구조 분해(Destructuring)

  • 할당 되는 값이 배열 형식으로 해야한다.
  • 순서의 개수를 맞춰야한다.
  • rest parameter 처럼 마지막에 사용할 수 있따.
const rank = ['1등', '2등', '3등', '4등', '5등'];
const first = rank[0];

 
const [first, second, third] = rank;
const [first, second, third, ...others] = rank;

console.log(first)
console.log(second)
console.log(third)
let macbook = 'me';
let ipad = 'you';

// temp 없이 값을 변경할 수 있다.
[macbook, ipad] = [ipad, macbook]

객체 구조 분해

  • 할당연사자의 이름과 배열의 속성 이름이 같아야한다.
  • 변수에 할당될 값이 없거나 혹은 undefined 값이 할당되면, 그 변수에는 undefined 대신 기본값이 할당된다. 단, null은 그래도 null 값을 가진다.
const macbook {
	title: '사고 싶다',
  	price: 10000000
}  

// const title = macbook.title;
// const pirce = macbook.price;

const {title, price} = macbook;
const {title:product, price} = macbook;	// title 이름을 변경할 수 있다.

console.log(title);
console.log(price);

function printSummary(object){
  const {title, price} = object;
	
  console.log(`${title}`);
  console.log(`${price}`);
} 


function printSummary({title, price}){	
  console.log(`${title}`);
  console.log(`${price}`);
} 

btn.addEventListener('click', (event) => {
  event.target.classList.toggle('checked');
}
                     
btn.addEventListener('click', ({target}) => {
	target.classList.toggle('checked');
}

btn.addEventListener('click', ({target: {classList}) => {
	classList.toggle('checked');
}

에러와 에러 객체

const error = new TypeError('타입 에러가 발생했습니다.');
throw error;

// try catch 문
try{
	// 코드
  console.log('에러 전');
  
  const codeit = '코드잇';
  console.log(codeit);
  
  codeit = 'codeit';
  
  const language = 'javascript';
  console.log(language);
  
} catch (error){
	// 에러가 발생했을 때 동작할 코드
  	console.log('에러 후');
  	console.log(error.name);
  	console.log(error.message);
}

활용하기

function printMembers(members){
	try{
      for (const member of mbembers){
      	console.log(member);
      }
    } catch (error) {
    	console.log(error);
     	alert(`${error.message} 가 발생했습니다. 콘솔창을 확인해주세요.`};
    }
}
const teamA = ['a', 'b', 'c', 'd'];
printMembers(teamA);

// 객체는 for ...of 를 사용할 수 없다.
const teamB = {'aa', 'bb', 'cc', 'd'};
printMembers(teamB);

const teamC = ['aaa', 'bbb', 'ccc', 'ddd'];
printMembers(teamC);

finally 문

try {
	// 실행할 코드
} catch (error) {
	// 에러가 발생했을 때 실행할 코드
} finally {
	// 항상 실행할 코드
}
profile
초조해하지 말자! 나는 충분히 할 수 있다! 인생은 길다!

0개의 댓글

관련 채용 정보