zero-wiki Help

코딩테스트 필수 문법

빌트인 데이터 타입

자바스크립트의 빌트인 데이터 타입은 언어 자체에서 제공하는 원시 타입과 참조 타입이 있습니다. 원시타입으로는 문자열, 숫자, 불리언 등이 있고, 참조 타입으로는 오브젝트 형태인 객체와 배열이 있습니다.

숫자

자바스크립트에서는 모든 숫자에 대한 값을 number 타입으로 정의합니다.

console.log(typeof 3); number console.log(typeof 0.5); number console.log(typeof 5.02); number console.log(typeof Infinity); number console.log(typeof NaN); number

자바스크립트는 수학 계산을 위해 여러 빌트인 함수를 제공합니다.

숫자 타입 산술 연산

const a = 10; const b = 4; // 연산자 console.log(a + b); // 더하기, 14 console.log(a - b); // 빼기, 6 console.log(a * b); // 곱하기, 40 console.log(a / b); // 나누기, 2.5 console.log(a % b); // 나머지, 2 console.log(-a); // 부호를 바꿉니다. // 빌트인 함수 console.log(Math.abs(-a)); // 절대값, 10 console.log(Math.ceil(a / b)); // 올림, 3 console.log(Math.floor(a / b)); // 내림, 2 console.log(Math.round(a / b)); // 반올림, 3 console.log(Math.trunc(-a / b)); // 버림, -2 console.log(Math.pow(a, b)); // a의 b승, 10000

숫자 타입 비교 연산

console.log(a == b); // 같은 값인지 비교 타입 검사는 유연함, 1 == "1", true console.log(a === b); // 같은 값인지 비교, 타입 검사를 엄격하게 함, 1 == "1", false console.log(a > b); // 왼쪽 값이 더 큰지 비교 console.log(a >= b); // 왼쪽 값이 더 크거나 같은지 비교

숫자 타입 비트 연산

console.log(a & b); // AND, 0 console.log(a | b); // OR, 14 console.log(a ^ b); // XOR, 14 console.log(~a); // NOT, -11 console.log(a<<2); // 왼쪽 시프트 (a에 2^2를 곱한 것과 동일), 40 console.log(a>>1); // 오른쪽 시프트 (a에 2^1로 나눈 것과 동일), 5

숫자 타입 논리 연산

console.log(a && b); // 논리 연산 AND / 4 console.log(a || b); // 논리 연산 OR / 10 console.log(!a); // 논리 연산 NOT / false

숫자 타입 예외

잘못 연산을 하는 경우 Infinity 혹은 NaN이 출력이 될 수 있습니다.

console.log(a / 0); // Infinity console.log(a % 0); // NaN console.log(a / "string"); // NaN console.log(a % "string"); // NaN console.log(a / null); // Infinity console.log(a % null); // NaN console.log(a / undefined); // NaN console.log(a % undefined); // NaN

부동 소수점 문제

자바스크립트에서 9.9 / 3.3를 한다면 3가 아닌 3.0000000000000004와 같은 숫자가 출력이 됩니다. 해당 이유는 자바스크립트가 부동소수점 데이터를 이진법으로 표현하기 때문입니다. 표현 과정에서 오차가 발생하는 겁니다. 이것을 우리는 엡실론이라고 표현합니다.

// 앱실론 출력 console.log(Number.EPSILON); // 2.220446049250313e-16 let a = 0.2 + 0.2 + 0.2; let b = 0.5; console.log(a - b); 0.10000000000000009 if (Math.abs(a - b) < Number.EPSILON) { console.log("a와 b는 같은 값입니다."); } else { console.log("a와 b는 다른 값입니다."); }

부동 소수점을 활용하는 문제는 오차 범위를 언급하는 범위가 많습니다. 문제 분석을 할 때 꼭 확인해야 하는 요소 중 하나입니다.

문자열

자바스크립트는 C++이나 Java의 Char 타입과 달리 글자 하나만 저장하는 타입이 따로 없습니다.

문자열 타입 정의

자바스크립트에서는 문자열을 지정하는 방법으로 작은 따옴표(''), 큰 따옴표(""), 백틱(``)으로 감싸는 방법이 있습니다.

문자열 활용 방법

여기서 백틱을 이용하여 표현식을 문자열 내에 넣을 수 있다는 특징이 있습니다. 해당 기능을 템플릿 리터럴이라고 부릅니다.

const userName = "Zero1016"; const printUserInfo = `Hello, ${userName}`;

백틱을 사용하면 여러 줄 문자열을 만들수 도 있습니다.

const stairs = ` * ** *** **** `;

문자열 타입 연산도 가능합니다.

console.log("user" + " is Zero1016"); // user is Zero1016 console.log("user is Zero" + "1016"); // user is Zero1016 console.log("Zero" + true); // Zerotrue

문자열 타입 빌트인 메서드

const introduce = "My name is Zero"; console.log(introduce.length); // 문자열의 길이를 구합니다. 15 console.log(introduce.split(' ')); // 특정 문자열 기준으로 나눕니다. // ['My', 'name', 'is', 'Zero'] console.log(introduce.startsWith('My')); // 특정 문자열로 시작하는지 확인합니다. true console.log(introduce.endsWith('Zero')); // 특정 문자열로 끝나는지 확인합니다. true console.log(introduce.includes('is')); // 특정 문자열로 포함하는지 확인합니다. true console.log(introduce.indexOf('name')); // 특정 문자열의 시작 위치를 확인합니다. 3 console.log(introduce.lastIndexOf('o')); // 특정 문자열의 마지막 위치를 확인합니다.14 console.log(introduce.replace('Zero', 'One')); // 특정 문자열을 다른 문자로 대체합니다 // My name is One console.log(introduce.toUpperCase()); // 대문자로 변환합니다. MY NAME IS ZERO console.log(introduce.toLowerCase()); // 소문자로 변환합니다. my name is zero console.log(introduce.trim()); // 양쪽 공백을 제거하니다. My name is Zero console.log(introduce.concat("!!")); // 문자열을 연결합니다. My name is Zero!!

그외 타입

불리언 타입

불리언 타입은 true와 false 값만 있는 자료형입니다. 보통 논리 연산의 결과로 나옵니다. 조건식을 만들거나 flag 용도로 사용되기도 합니다.

bigint 타입

큰 수를 다룰 때 사용할 수 있습니다. 기존 숫자 타입은 큰 수를 다루는 경우 연산 결과가 이상할 수 있습니다. 이때 bigint 타입을 사용해줄 경우 방지할 수 있습니다.

숫자 뒤에 n이나 Bigint()를 통해 만든다면 bigint 타입을 사용할 수 있습니다.

undefined 와 null 타입

undefined는 변수가 초기화 되지 않았을 때 적용되는 타입입니다. 반면 null은 개발자가 의도적으로 비어 있다는 것을 표현하기 위해 넣는 값이자 타입입니다.

참조 타입

참조 타입은 오브젝트 타입과 함수 타입만 있습니다.

오브젝트

오브젝트 타입 선언

오브젝트 타입은 중괄호 안쪽에 키와 값을 적는 것으로 정의할 수 있습니다. 만약 키에 특수 문자가 들어가는 경우 따옴표로 감싸야 합니다.

const user = { name: 'Zero', age: 20, 'full-name': 'Zero1016' }; console.log(user.name); // Zero console.log(user['full-name']); // Zero1016

요소 추가

요소 추가를 할 경우 값을 단순하게 대입하는 것으로 추가할 수 있습니다.

user.job = 'frontend-developer'; console.log(user.job); // frontend-developer

요소 삭제

delete 키워드를 사용하면 오브젝트 내 요소를 삭제할 수 있습니다.

delete user.job; console.log(user.jobs); // undefined

함수

자바스크립트에서 함수는 일반적인 정의도 가능하지만 일급 객체이자 타입입니다.

코딩 테스트 코드 구현 노하우

자바스크립트는 문법을 더 쉽고 객관적으로 사용할 수 있게 문법적 편의 기능을 제공합니다. 문법 특징을 이용한 트릭을 더하면 더 편하고 빠르게 원하는 로직을 구현할 수 있습니다.

구조 분해 할당

// 배열의 경우 const arr = ['My', 'name' 'is', 'zero']; const [first, second] = arr // 객체의 경우 const user = { name: 'zero1016', age: 20 }; const { name, age } = user;

구조 분해 할당을 이용한다면 위와 같이 값들을 손쉽게 꺼내서 사용할 수 있습니다.

  1. 배열의 경우 인덱스 번호를 이용하여 접근이 가능합니다. 예를 들어 [fist, second]만 꺼냈을 경우 배열의 길이가 2이므로 arr 배열에서 첫번째와 두번째 배열의 값만 사용할 수 있습니다.

  2. 객체의 경우 키값을 이용한 구조분해 할당을 사용하여 손쉽게 가져올 수 있습니다.

값 교환하기

구조 분해 할당을 이용하면 변수의 값을 교환하는 로직을 간단하게 구현할 수 있습니다.

let a_name = 'Zero'; let b_name = 'One'; let temp; temp = a_name; a_name = b_name; b_name = temp; [a_name, b_name] = [b_name, a_name];

비구조화 할당

함수에 객체를 인수로 전달할 경우 필요한 것만 꺼내서 사용할 수 있는 문법 기능입니다.

const calculator_add = ({ num1, num2 }) => { return { result: num1 + num2, num1, num2 } }; const result = calculator_add({ num1: 10, num2: 20, num3: 30 }); console.log(result); /* { result: 30, num1: 10, num2: 20 } */

스프레드 연산자

스프레드 연산자를 사용하여 여러 개를 하나로 합칠 수 있습니다.

const oddNumber = [1, 3, 5, 7, 9]; const evenNumber = [2, 4, 6, 8, 10]; const numbers = [...oddNumber, ...evenNumber]; console.log(numbers); // [1, 3, 5, 7, 9, 2, 4, 6, 8, 10] const person = { name: "Zero1016", country: "korea" }; const address = { country: undefined, city: 'Seoul' }; const mergeInfo = { ...person, ...address }; console.log(mergeInfo); /* { name: 'Zero1016', country: undefined, city: 'Seoul' } */

배열과 객체의 경우 위와 같이 스프레드 연산자를 통해 병합을 할 수 있습니다. 한가지 주의해야 할 점은 객체의 경우 같은 키 값을 가진 객체가 병합이 될 때 뒤에 오는 객체가 덮어 씌운다는 점입니다.

배열 내 중복 요소 제거하기

문제를 풀다보면 배열 내 같은 요소를 제가할 때가 있습니다. 스프레드 연산자와 Set 객체를 이용하면 손쉽게 제거할 수 있습니다.

const alpa = ['a', 'b', 'c', 'd', 'b', 'd']; const uniqueAlpa = [...new Set(alpa)]; console.log(uniqueAlpa); // ['a', 'b', 'c', 'd']

&&와 || 연산자로 조건문 대체하기

자바스크립트에서는 &&와 || 연산자를 사용하여 조건문을 대체할 수 있습니다. 보통 &&연산자는 앞 요소를 플래그로 사용하여 플래그가 true면 뒤 요소를 실행할 때 사용합니다.

// temp가 true일 경우 func 함수가 실행됩니다. temp && func(); // 객체 병합에도 사용할 수 있습니다. const makeCompany = (showAddress) => { return { name: 'rabbit', ...showAddress && { address: 'Seoul' } // showAddress가 true면 뒤 객체에 스프레드 연산자를 적용합니다. } }
Last modified: 07 August 2024