JavaScript

[JavaScript] JavaScript 문법

수박쓰123 2023. 3. 16. 13:28

Destructing

destructing: 배열이나 객체의 속성을 해체하 그 값을 변수에 담을 수 있 하는 ES6 문법
 
 const player = {
   name: 'Kyle',
   club: 'None',
   address: {
     city: 'La'
   }
 }

player 안의 내용들을 출력하기 위해서는

console.log(player.address.name, player.address.club, player.address.city)

라는 출력 구문이 필요하다.

 

하지만 이 코드는 길고 비효율 적이다.

이것을 해결하기 위해 destructing 문법을 사용한다면 출력을 구문을 훨씬 간단하게 사용할 수 있다.

const { name, club, address: {city}} = player
console.log(name, club, city)

첫 줄에는 본래 player 안에 있던 값들을 destructing 문법을 통하여 분해 후 다시 player 변수에 넣는 것을 볼 수 있다.

그리고 마지막 출력은 다시 정의한 name, club, city만 적어준다면 아까보다도 훨씬 쉽게 사용할 수 있다.


For 문

for 문은 프로그램 내에서 특정한 작업을 반복적으로 실행할 수 있도록 해주는 반복문의 종류 중 하나이다.

let imcomes = [3500, 3700, 4000];
let total = 0;

for (const imcome of imcomes) {
  console.log(imcome)
  //첫 번째 출력 -> 3500
  //두 번째 출력 -> 3700
  //세 번째 출력 -> 4000
  total += imcome
}
console.log(total)
//3000 + 3700 + 4000 = 10700

Template literal

`(백틱)을 사용하면 문자열 내에서 변수를 사용할 수 있다.

console.log(`Hi! My name is ${변수 이름}!`);

Spread Operator

스프레드 연산자는 배열, 문자열, 객체 등 반복 가능한 객체를 개별적으로 분리시킬 수 있다.

let contacts = ["Mary", "Joel", "Danny"]
let personalFriends = ["David", ...contacts,"Lily"]
console.log(personalFriends) //출력 -> David Joeal Danny + Lily

출력 결과를 보면 ...(스프레드 연산자)를 사용하여 contacts의 값들이 personalFriends에 들어간 것을 알 수 있다.


Funtion

Anonymous function

자바스크립트의 익명 함수(anonymous function)은 변수에 함수 코드를 저장하는 대신 함수명을 사용하지 않는다. 대신 변수명을 함수명처럼 사용해서 함수를 호츨하거나 수정하는 등에 작업을 할 수 있다.

const lunchMenu = function() {
  return "I'm going to eat pizza for lunch"
}
console.log(lunchMenu())

 

Arrow function

화살표 함수는 함수 표현식보다 단순하고 간결한 문법으로 함수를 만들 수 있는 방법이다.

const dinnerMenu = () => {
  return "I'm going to eat pizza for dinner"
}
console.log(dinnerMenu() )

 

const dinnerMenu2 = () => "I'm going to eat pizza for dinner"
console.log(dinnerMenu2())

 

const dinnerMenu3 = (food) => `I'm going to eat ${food} for dinner`
console.log(dinnerMenu3('chicken'))

 

const dinnerMenu4 = food => `T'm going to eat a ${food} for dinner`
console.log(dinnerMenu4('raw tuna'))

 

const dinnerMenu5 = (food = 'burger') => `I'm going to eat a ${food} for dinner`
console.log(dinnerMenu5())

 


includes

includes 문법은 문자열이 특정 문자열을 포함하는 확인하는 메서드이다.

let numArray = [1, 2, 3, 4, 5];
console.log(numArray.includes(7));

'var' vs 'let' vs 'const'

var: 재선언 되고, 업데이트를 할 수 있다.

let: 업데이트는 가능하지만, 재선언은 불가능하다.

const: 업데이트도 재선언도 불가능한다.


promise

promise는 Javascript 비동기 처리에 사용되는 객체이다. 여기서 비동기 처리란 '특정 코드의 실행이 완료될 때까지 기다리지 않고 다음 코드를 먼저 수행하는 자바스크립트의 특성'을 의미한다.