[ 7주차 - 0923 ]
금일 커리큘럼
├ 09:00 ~ 12:00 FrontEnd (JS 개념, 변수와 상수, 데이터 타입, 연산자, 조건문)
└ 13:00 ~ 18:00 FrontEnd (함수, 객체, 배열)
1. JS 개념
JavaScript : 웹 브라우저에서 사용하기 위해 만들어진 프로그래밍 언어
- HTML(구조), CSS(디자인)와 함께 웹의 3대 핵심 기술
- 현재는 브라우저뿐만 아니라 Node.js를 통해 서버에서도 사용됨
기본 특징
- 1. 동적 타입 : 변수선언시 자료형 지정안해도됨
- 2. 객체 기반 : js 모든 것은 객체로 이루어짐 (array,func 도)
- 3. DOM 조작 : dom 접근하여 html 태그의 내용,속성,스타일 등 제어
- 4. 이벤트 기반 : 사용자 행동에 반응해서 코드 실행가능 (클릭,호버,스크롤,터치 등)
// 1. 동적 타입
let value = 10; // 숫자
value = "안녕 JS"; // 문자열로 변경
console.log("value:", value);
// 2. 객체 기반 (배열, 함수도 객체)
const arr = [1, 2, 3];
const add = function(a, b) { return a + b; };
console.log("배열 길이:", arr.length);
console.log("함수 실행:", add(5, 7));
// 3. DOM 조작
const title = document.querySelector("h1");
title.style.color = "blue";
title.innerText = "JavaScript로 변경됨!";
// 4. 이벤트 기반
document.querySelector("button").addEventListener("click", () => {
alert("버튼 클릭됨!");
});
ES5, ES6 차이
ES (ECMAScript) : JS 언어의 규칙, 세부사항, 지침 등을 정의하는 표준 문법
- ES5 : 2009년 업데이트 된 버전
- ES6 : 2015년 ~ 2019년까지 업데이트 된 버전
ES6에서 변화
- let,const 키워드 추가 - val 키워드 단점 보완
- 화살표함수 추가 - 간결표현식
- 템플릿 리터널 백틱 제공 - `${ }` 통해서 바인딩 가능
<script type="module" src="..."></script>지원
// module.js
export const PI = 3.14;
// main.js
import { PI } from './module.js';
2. JS 변수와 상수
- 변수(Variable) : 데이터를 저장할 수 있는 공간
- 상수(Constant) : 한 번 값이 정해지면 바꿀 수 없는 공간
선언 방식
- let : 재할당 가능 (ES6+)
- const : 상수, 재할당 불가 (ES6+)
- var : 재할당 가능, 호이스팅 문제있음 (ES5-)
호이스팅이란?
- 자바스크립트 엔진이 코드를 실행할 때 변수 선언을 코드 맨 위로 끌어올려 놓는 것처럼 동작하는 현상
- 코드순서가 아닌 내부적으로 선언 → 초기화 → 실행 순서로 처리
/** var와 호이스팅 */
console.log(_a) // undefined (var _a; 로 선언만 끌어올림)
var _a = 1;
var _a = "안녕"; // 재선언 오류없음 덮어씌워짐
/** let */
let _b = 1;
//let _b = 2; // error
_b = "반가워"; // 재할당 가능
/** const */
const _c = 1;
// const _c = 2; // error
// _c = 2; // error
3. 데이터 타입
String 문자열
let _msg = "안녕하세요";
_msg = _msg + "!";
// 객체 리터럴
let _a = 10, _b = 20;
let _sumMsg = `${_a} + ${_b} = ${_a + _b}`;
let _str = ' Hello JS ';
console.log(_str.trim()); // 'Hello JS'
console.log(_str.toUpperCase()); // ' HELLO JS '
console.log(_str.toLowerCase()); // ' hello js '
console.log(_str.includes('JS')); // true
console.log(_str.indexOf('o')); // 5
console.log(_str.replace('JS', '2')); // ' Hello 2 '
console.log(_str.split(' ')); // ['', 'Hello', 'JS', '']
console.log(typeof _str); // "string"
boolean
let _check;
_check = true;
_check = false;
console(typeof _check); // "boolean"
null, NaN, undefined
- null : 값 없음을 명시적으로 지정
- NaN : Not a Number (숫자가 아님)
- undefined : 선언은 되었지만 값이 없는 상태
/* null ------------- */
let _val = null;
console.log(_val); // null
console.log(typeof _val); // "object" (자바스크립트 설계 오류로 이렇게 나옴)
// 다른예시
let _el2 = document.querySelector(".no-class");
console.log(_el2); // null
function findUser(id) { return null; }
console.log(findUser(1)); // null
/* NaN ------------- */
let _result = 0 / 0;
console.log(_result); // NaN
console.log(typeof _result); // "number"
/* undefined ------------- */
let _data;
console.log(_data); // undefined
console.log(typeof _data); // "undefined"
// 다른예시
function findUser2(id) { };
console.log(findUser2(1)); // undefined
let _obj = {};
console.log(_obj.age); // undefined
null 과 undefined 차이
null → 그릇(변수)이 있는데 의도적으로 값이 없음
- 변수가 있긴 하지만, 그 안에 “아무 값도 없다(null)” 라고 개발자가 직접 넣은 것
- 주로 값이 있어야 하는데 지금은 없음 을 나타낼 때
undefined → 그릇(변수)은 있는데 아직 값이 정해지지 않음
- 변수를 선언만 했지만 값을 할당하지 않은 상태
let _a; - 객체/배열에서 존재하지 않는 속성이나 인덱스를 접근했을 때
- 함수에서 return이 없을 때 자동 반환
4. 연산자
산술연산
let _a = 10 + 5; // 15
let _b = 10 - 5; // 5
let _c = 10 * 5; // 50
let _d = 10 / 5; // 2
let _e = 10 % 3; // 1 (나머지)
비교연산
// == 동등한지 비교함 - 비권장
console.log(5 == '5'); // true
// === 정확히 비교함
console.log(5 === 5); // true
console.log(5 === '5'); // false
console.log(5 !== '5'); // true
// 크기 비교
console.log(10 > 5); // true
console.log(10 >= 10); // true
논리연산
// and (&&)
console.log(true && true); // true
console.log(true && false); // false
// or (||)
console.log(true || false); // true
console.log(false || false); // false
// not (!)
console.log(!true); // false
console.log(!false); // true
삼항연산
// 일반
const _age = 20;
console.log(_age >= 18 ? '성인' : '미성년');
// 중첩방식
const _hour = 23;
const _test =
(0 <= _hour && _hour < 6) ? '새벽'
: _hour < 12 ? '아침'
: _hour < 18 ? '오후'
: _hour < 24 ? '저녁'
: '잘못된 시간';
console.log(_test); // 저녁
5. 조건문
const _age = 20;
let _msg;
// if 문
if(_age >= 18) _msg = '성인';
else if (_age >= 13) _msg = '청소년';
else _msg = '유아';
// switch 문
switch (_msg) {
case '성인' :
_msg += ', 구매 가능'
break;
case '청소년' :
case '유아' :
_msg += ', 구매 불가'
break;
default :
break;
}
console.log(_msg); // 성인, 구매 가능
6. 함수 function
JS에서 함수 방식
- 함수 선언식 : function 키워드 선언 (선언 전 호출가능 = 호이스팅)
- 함수 표현식 : 변수에 함수를 할당 (선언 이후에만 호출가능)
- 화살표 함수 : 간결하게 표현. 자기자신 this 바인딩 없음
// 함수 선언식
console.log(add(1,2)); // 호이스팅
function add(a, b) { return a + b };
// 함수 표현식
const divide = function (a, b) { return a / b };
// 화살표 함수 (ES6+)
const multiply1 = (a, b) => a * b; // 기본 리턴
const multiply2 = (a, b) => { return a * b };
화살표 함수에서 this 가르키는 곳은?
- 화살표 함수는 자기만의 this를 생성하지 않는다.
- 따라서 어떤 객체의 메서드로 호출하더라도, 화살표 함수 안의 this는 정의된 위치의 상위 스코프를 캡처한다.
- 전역(브라우저)에서 정의되었다면 window
- ES 모듈/strict 모드라면 undefined
const _val = "global";
const funcObj = {
_val: "obj",
func0() { console.log(this._val) },
func1: function() { console.log(this._val) },
func2: () => { console.log(this._val) },
};
funcObj.func0(); // obj (선언함수 this = funcObj)
funcObj.func1(); // obj (표현함수 this = funcObj)
funcObj.func2(); // global (상위스코프 캡처됨 - 전역)
/**
* func0 / func1
* 객체의 메서드로 실행되므로 this가 funcObj를 가리킴
* ---------
* func2 (화살표 함수)
* 객체 안에 있더라도 this를 새로 바인딩하지 않음
* 정의된 상위 스코프가 전역이므로 this._val = "global"
*/
7. 객체 object
객체 생성 및 접근
- 객체 생성 : {} 중괄호 안에 속성(key: value)과 메서드를 정의
- 속성 접근,수정,추가,삭제 가능하나 키값은 변경 불가
// 객체 생성
const user = {
name: '김철수',
age: 20,
addr: '서울시',
male: true,
hobbies: ['여행', '독서', '게임'],
sayHi: function() {
console.log(`안녕하세요. ${this.name}입니다.`);
}
};
// 속성 접근
console.log(user.name); // 김철수
console.log(user['age']); // 20
// 속성 수정
user.hobbies[0] = '영화';
// 속성 추가
user.email = 'test@example.com';
// 속성 삭제
delete user.addr;
// 메서드 호출
user.sayHi(); // 안녕하세요, 김철수입니다.
console.log(user);
객체 구조 분해
- 구조 분해 할당 : 객체 속성을 꺼내 변수에 바로 할당 가능
- 변수명 변경 :
const { key: 새이름 }= 객체 형태로 값은 그대로, 변수명만 변경
const product = {
id: 101,
name: '노트북',
price: 1200000,
brand: '삼성',
specs: {
cpu: 'i9',
ram: '16GB',
ssd: '512GB'
}
};
// 기본 구조 분해
const { id, name, price } = product;
console.log(id); // 101
console.log(name); // 노트북
console.log(price.toLocaleString()); // 1,200,000
// 변수명 변경 - 실제 반영x (대입임)
const { brand: maker } = product;
console.log(maker); // 삼성
// 내부 중첩 분해
const { specs: { cpu, ram } } = product;
console.log(cpu); // i9
console.log(ram); // 16GB
// 함수로 파라매터
function consoleProd({ name, price }) {
console.log(`${name}의 가격은 ${price.toLocaleString()}원 입니다.`);
}
consoleProd(product);
// 노트북의 가격은 1,200,000원입니다.
getter & setter
- 보통 get,set만들때 필드변수를
_변수명으로 쓰고, get,set 키워드에 변수네이밍 사용함
const user2 = {
// 필드변수
_name: "김철수",
// getter
get name() {
return this._name;
},
// setter
set name(newName) {
this._name = newName;
}
};
console.log(user2.name); // 김철수 (getter)
user2.name = "홍길동"; // setter
console.log(user2.name); // 홍길동 (getter)
console.log(user2._name); // 직접 접근되나.. 비권장
자바와 다르게 네이밍을 getName, setName으로 안하는 이유?
1. 자바
- 자바는 자바는 클래스 기반, 메서드 호출 중심 언어임
- 프로퍼티를 직접 접근할 수 없으니,
getName(),setName()같은 메서드 형태로 속성 접근을 강제
2. 자바스크립트
- JS의 get set은 객체 프로퍼티 접근을 확장한 문법
user2.name을 읽거나 쓸 때, 엔진이 자동으로 getter/setter 함수를 실행- 그래서
get name() {}/set name() {}처럼 프로퍼티 이름을 그대로 씀
Q. 그냥 맞추면되지않을까?
- 문법상 동작은 가능하지만, 그건 사실상 일반 메서드와 똑같아집
- 즉,
user2.getName이라고 쓰면 getter로서 프로퍼티 접근이 아니라 그냥getName이라는 메서드 호출임user2.name으로하면 프로퍼티 접근하여, get set 키워드로 정의한 함수를 대신 실행
8. 배열
배열 기본
// 생성
const strs = ['안','녕','js'];
const nums = [1,2,3,4,5];
// 접근
console.log(strs[2]); // js
console.log(nums[1]); // 2
// 수정
strs[0] = 'H';
console.log(strs[0]); // H
// 길이
console.log(strs.length); // 3
배열 메서드
const arr0 = [1,2,3];
arr0.push(4); // 끝에 추가 : 1,2,3,4
arr0.pop(); // 끝에서 제거 : 1,2,3
arr0.unshift(0); // 앞에 추가 : 0,1,2,3
arr0.shift(); // 앞에서 제거 : 1,2,3
// 병합
const arr1 = [4,5];
const arr2 = arr0.concat(arr1); // 1,2,3,4,5
// 범위추출, 범위삭제
console.log(arr2.slice(0,2)); // 0~2 만뽑음 : 1,2
arr2.splice(0,1); // 0~1 삭제 : 2,3,4,5
console.log(arr2);
// 순서변경
arr2.reverse(); // 뒤집기 : 5,4,3,2
arr2.sort(); // 오름차순 : 2,3,4,5
arr2.sort((a,b) => b - a); // 내림차순 : 5,4,3,2
// 탐색
console.log(arr2.indexOf(3)); // idx찾기 : 2 (없으면 -1)
console.log(arr2.includes(2)); // 포함여부 : true
console.log(arr2.find(n => n > 3)); // 조건true 첫요소값 : 5 (없으면 undefined)
console.log(arr2.filter(n => n > 3)); // 조건true 전체요소 : [5,4] (없으면 [])
console.log(arr2.findIndex(n => n > 3)); // 조건true 첫요소 idx : 0 (없으면 -1)
// 문자열로 확인
console.log(arr2.toString()); // 5,4,3,2
console.log(arr2.join('-')); // 5-4-3-2
스프레드 연산, 배열복사, 배열 분해
- 스프레드 연산은 ES6+(2015) , 객체는 ES9+(2018) 이상에서 가능
- 얕은 복사(shallow copy) vs 깊은 복사(deep copy) 차이를 주의해야 함
// 스프레드 연산자 (...)
const arrA = [1, 2, 3];
const arrB = [4, 5, 6];
const combined = [...arrA, ...arrB]; // [1, 2, 3, 4, 5, 6]
// 복사
const copyArr0 = arrA; // 주소복사 (얕은복사)
const copyArr1 = [...arrA]; // 1차원 깊은복사 (다차원은 x)
copyArr0[0] = 100;
copyArr1[1] = 200;
console.log(arrA, copyArr0, copyArr1);
// 다차원 깊은 복사
const deepArr = [[1,2], [3,4]];
const copyDeepArr = deepArr.map(inner => [...inner]);
copyDeepArr[0][0] = 100;
console.log(deepArr, copyDeepArr);
// 배열 구조분해 할당
const [first, second, ...rest] = [1, 2, 3, 4, 5];
console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3, 4, 5]
// 값 교환
let x = 10, y = 20;
[x, y] = [y, x];
console.log(x, y); // 20, 10'멋사 - 부트캠프 19기 : Java > FrontEnd' 카테고리의 다른 글
| (09.25 ①) Front 기초 - DOM 개념, 요소 선택, 요소 제어, 이벤트 처리 (0) | 2025.09.25 |
|---|---|
| (09.24) Front 기초 - JS 배열 메서드, 객체 순회, 클래스, 프로토타입, 비동기 (0) | 2025.09.24 |
| (09.22) Front 기초 - css 크기 단위, display, position (0) | 2025.09.22 |
| (09.19) Front 기초 - CSS, CSS 선택자, cascading (0) | 2025.09.19 |
| (09.18) Front 기초 - 웹 역사와 HTML, 개발 환경 구축, Node.js, html 주요태그 (0) | 2025.09.18 |