티스토리 뷰

WEB/JavaScript

[JavaScript] 연산자와 구문

devOhzl 2023. 12. 12. 10:09

Nullish 병합 연산자

📌 AND / OR 연산자

1️⃣ && : 제일 먼저 만나는 false를  반환 , 모두가 true 이면 가장 마지막 데이터 반환

2️⃣ || : 제일 먼저 만나는 true를 반환 , 모두가 false 이면 가장 마지막 데이터 반환

console.log('a' && 0)		// 0
console.log('a' && 'b' && 'c')	// c
console.log(0 || 7)		// 7
console.log(0 || 8 || 9 )	// 8

 

📌 Nullish 연산자

&&, || 연산자와 동일하게 왼쪽에서 오른쪽으로 해석하지만,  null ,undefined 를 제외한 먼저 만나는 데이터를 반환한다.

모두 null 또는 undefined면 가장 마지막 데이터 반환

console.log(0 ?? 7)			// 0
console.log(null ?? 1)			// 1
console.log(null ?? undefined)		// undefined

전개 연산자 (Spread Operator)

Array, 반복 가능한 객체 등의 요소를 전개하거나 펼친다.

const a = [1,2,3]
console.log(a)		// [1,2,3]
console.log(...a)	// 1,2,3

📌 데이터 합치기

1️⃣ 배열 

concat 메서드를 사용할 수도 있지만, 전개 연산자를 사용하면 배열 데이터의 대괄호를 날리며 배열을 합쳐준다.

const a = [1,2,3]
const b = [4,5,6]

const c = a.concat(b)
console.log(c)		// [ 1, 2, 3, 4, 5, 6 ]

const d = [ ...a, ...b ]
console.log(d)		// [ 1, 2, 3, 4, 5, 6 ]

2️⃣ 객체

Obejct.assign을 사용할 수도 있지만, 전개 연산자를 사용하면 객체 데이터의 중괄호를 날리며 객체를 합쳐준다.

const a = { x: 1, y: 2 }
const b = { y: 3, z: 4 }

const c = Object.assign({}, a, b)
console.log(c)		// { x: 1, y: 3, z: 4 }

const d = {...a, ...b}
console.log(d)		// { x: 1, y: 3, z: 4 }

 

📌 Rest Parameter

전개 연산자를 매게변수로 사용한다.

function fn(...data){
  console.log(data)
}

fn(3)		// [3]
fn(1,2,3)	// [1,2,3]
function fn(x,y,z){
  console.log(x,y,z)
}

fn(1,2,3)		// 1,2,3

const a = [4,5,6]
fn(a)			// [ 4, 5, 6 ] undefined undefined=
fn(...a)		// 4 5 6

구조 분해 할당

📌 배열

구조를 분해해서 각각의 변수에 재할당을 하는 방법

 

1️⃣ 배열 데이터 혹은 객체 데이터의 구조를 분해해서 구조에 맞게 각각의 변수에다가 개별적으로 데이터를 할당한다.

const arr = [1,2,3]
;[a,b,c] = arr
console.log(a,b,c)	// 1,2,3

대괄호나 소괄호로 시작할 때는 앞에 세미콜론을 붙여 시작할 수도 있다.

 

2️⃣ 필요하지 않은 변수가 있으면 제거를 해도 된다.

하지만 구조를 맞춰서 순서대로 변수에 할당하므로 쉼표를 이용해 사용하지 않는 자리는 비워줘야한다.

const arr = [1,2,3]
;[,b,c] = arr
console.log(b,c)	// 2,3

배열 데이터에서 사용할 때는 순서가 중요하다 ! 

 

3️⃣ 선언하지 않은 나머지 모든 데이터를 전개 연산자를 사용해서 하나의 변수에 몰아둘 수 있다.

const arr = [1,2,3]
const [a, ...rest] = arr
console.log(a,rest)		// 1 [2,3]

 

📌 객체

배열은 값이 대괄호 안에서 나열되어 있기 때문에 무조건 순서를 맞춰 구조분해할당을 해야 하지만

1️⃣ 객체는 속성 이름이 부여되어 있으므로 속성 이름으로  원하는 데이터를 바로 찾을 수 있다.

const obj = {
  a: 1,
  b: 2,
  c: 3
}

const { a, b } = obj;
console.log(a,b)	// 1,2

 

2️⃣ 객체 데이터에 특정한 속성이 없을 경우를 대비하여 기본값을 정의할 수 있다.

const obj = {
  a: 1,
  b: 2,
  c: 3,
  y: 5
}

const { x = 4 } = obj
console.log(x)	// 4

const { y = 0 } = obj
console.log(y)	// 5

 

3️⃣ 가져오는 객체 속성의 이름을 변경할 수 있다.

const obj = {
  a: 1,
  b: 2,
  c: 3
}

const { a: data } = obj
console.log(data)	// 1
console.log(a)		// ReferenceError: a is not defined

 

4️⃣ 2+3 둘다 적용 할 수 있다.

const obj = {
  a: 1,
  b: 2,
  c: 3
}

const { y:ten = 30 } = obj
console.log(ten)	// 30
console.log(y)		// ReferenceError: y is not defined

 

3️⃣ 선언하지 않은 나머지 모든 속성들은 전개 연산자를 사용해서 변수에 한번에 할당할 수 있다.

const obj = {
  a: 1,
  b: 2,
  c: 3,
  x: 7,
  y: 100
}

const { c, ...rest } = obj
console.log(c, rest)		// 3, { a: 1, b: 2, x: 7, y: 100 }

선택적 체이닝

물음표 앞쪽에 있는 데이터가 null 이나 undefined 라면 뒤쪽의 내용을 실행하지 않고 undefined를 반환한다.

→ 에러를 발생시키지 않고 단순하게 undefined를 출력한다. 

const user = null
console.log(user.name)	// TypeError: Cannot read properties of null (reading 'name')
console.log(user?.name)	// undefined
const userA = {
  name: 'AERI',
  age: 25,
  address: {
    country: 'Korea',
    city: 'Seoul'
  }
}
const userB = {
  name: 'Neo',
  age: 22
}

function getCity(user){
  return user.address?.city || '주소 없음'
}

console.log(getCity(userA))	// Seoul
console.log(getCity(userB))	// 주소 없음

반복문

📌 for

  • break : 전체 반복을 종료한다.
  • continue : 현재 반복을 종료하고 다음 반복으로 넘어간다

📌 for of

배열을 반복한다

const users = [
  {
    name: 'Aeri',
    age: 26
  },
  {
    name: 'Neo',
    age: 23
  },
  {
    name: 'Lin',
    age: 30
  }
]

for (const user of users){
  console.log(user.name)	
  // { name: 'Aeri', age: 26 },{ name: 'Neo', age: 23 },{ name: 'Lin', age: 30 }
}

 

📌 for in

객체를 반복한다

const user = {
  name: 'Aeri',
  age: 26,
  isValid: true,
  email: 'kar2125@naver.com'
}

for(const key in user){
  console.log(key)	// 'name','age','isValid','email'
}

 

📌 while

조건이 참이면 계속 반복한다. 👉 무한반복 조심

let n = 0;
while(n < 3){
  console.log(n);	// 0,1,2
  n += 1
}

 

📌 do while

do 키워드의 중괄호를 먼저 실행하고, while 키워드로 넘어가서 조건을 실행한다.

👉 조건이 거짓이라도 최초 한번은 실행한다.

let n = 0

do {
  console.log(n)	// 0
} while (n)
let n = 0

do {
  console.log(n)	// 0,1,2
  n += 1
} while (n < 3)

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함