어쩌다 알게 된 ƪ(•̃͡•̃͡ ƪ

자바스크립트 생명주기 본문

자바스크립트/⚪️ Vanilla

자바스크립트 생명주기

비니_ 2025. 2. 25. 11:00
728x90

자바스크립트 생명주기

 

1. 로딩 단계 (Loading Phase)
- 웹 페이지가 로드되면 HTML, CSS, 자바스크림트 파일이 브라우저에 의해 로드
- <script> 태그가 문서에 위치한 곳에 따라 자바스크립트가 실행
- <head>에서 로드된 스크립트는 DOM이 완전히 로드되기 전에 실행될 수 있으며, <body> 끝에 위치한 스크립트는 DOM이 모두 로드된 후 실행

2. 실행 단계
- 페이지가 로드된 후, 브라우저는 HTML 문서를 파싱하여 DOM을 구축하고, 자바스크립트 코드가 실행
- 자바스크립트가 실행되는 시점은 DOMContentLoaded 이벤트나 window.onload와 같은 이벤트에 의해 실행

3. 업데이트 단계
- DOM에 대한 변경이 이루어질 때마다 브라우저는 다시 랜더링을 하여 최신 상태를 화면에 반영
- 예를 들어, 자바스크립트에서 innerHTML, style, class 등을 수정하는 경우 화면에 즉시 반영

4. 소멸 단계 (마케팅 기간 설정할 때 사용할 수 있음- 사용자가 머무는 시간 가져올 수 있기에)
- 사용자가 페이지를 떠나거나 DOM 요소가 제거되면 해당 요소에 관련된 이벤트리스너와 데이터들이 메모리에서 해제
- window.onunloaded, window.onbeforeunload 이벤트는 페이지가 종료되거나 새로고침될 때 발생 (새로고침해도 페이지를 떠난다고 인식)
** window.onunloaded : return false; // 페이지 최초 진입 시점 한 번 만 떠나기 전에 다이얼로그 생성


연산자

1. null 병합 연산자 (삼항 연산자와 비슷)
- 좌측 값이 null 또는 undefined인 경우: 우측 값을 반환
- null 또는 undefined가 아닌 경우: 좌측 값을 반환
- ?? 형태로 사용

let result = value1 ?? value2;
- value1이 null 또는 undefined라면 value2를 반환
- 그렇지 않으면 value1을 반환

ex)
let name = null;
let defaultName = 'Unknown';
let display = name ?? defaultName;
cosole.log(display); // Unknown

----------------------------------------------------------------------------------
📌 옵셔널 체이닝이란? (병합 연산자와 비슷) ** 요즘 생긴 방식
- 객체의 프로퍼티에 접근하거나 메서드를 호출할 때, 안전하게 접근할 수 있도록 도와주는 연산자
- 객체나 프로퍼티가 null 또는 undefined 인지 확인하고, 에러를 방지하기 위해 사용
- 중첩된 객체 구조에서 유용하며, 값이 없더라도 에러 없이 undefined를 반환
- 동적으로 결정될 때 대괄호 및 함수 표기법을 다르게 표시
- 쓰기에는 사용할 수 없고 읽기에만 사용

1. obj?.property
- obj가 null 또는 undefined인 경우 에러 대신 undefined를 반환하고 그렇지 않으면 obj?.property를 반환

2. obj?.[expression]
- 객체의 속성이 이름이 동적으로 결정될 때 사용
예제)

3. obj?.method()
- 객체의 메서드(함수)를 호출하려고 할 때 사용하며, 객체가 존재하지 않으면 undefined를 반환

**
1. 기본 사용법
const user = {
  profile : {
    name: 'Alice'
  }
}

console.log(user.profile.name);
console.log(user.profile?.name); // profile이 있는지 없는지 모를 때
console.log(user.profil?.name); // undefined
console.log(user.profile?.age); // undefined
console.log(user?.profile?.age); // undefined
console.log(user?.aa.age); // 에러
console.log(user?.aa?.age); // undefined

**사용하는 이유: 에러가 나면 밑에 스크립트들이 작동을 안하지만 옵셔널 체이닝을 사용하면 undefined를 반환하고 밑에 스크립트들을 동작 시킬 수 있음

2. 메서드 호출
const user = {
  greet: function(){
    return 'Hello!!';
  }
}
console.log(user.sayHi?.()); // undefined
console.log(user.greet());

3. 배열 접근
const users = [
  {name:'Bob'},
  null,
  {name:'Charlie'}
];

console.log(users[0].name); // Bob
console.log(users[1].name); // 에러
console.log(users[2].name); // 실행 안 됨

console.log(users[0]?.name); // Bob
console.log(users[1]?.name); // undefined
console.log(users[2]?.name); // Charlie

4. 동적 속성 접근
const settings = {
  theme: {
    darkMode: true
  }
};

const key = 'darkMode';

console.log(settings.theme?.[key]); // true
console.log(settings.display?.[key]);

5. 쓰기 불가
const obj = {};
obj.prop = 42; // 42
obj?.prop = 42; // 에러 (쓰기 불가 읽기만 가능)

6. 기본값 설정
- 옵셔널 체이닝과 ?? 연산자를 좋바하면 기본값을 설정하기에 유용

let user = null;
let userName = user?.name ?? 'Guest';
console.log(userName);

----------------------------------------------------------------------------------
📌 자바스크립트 정규 표현식(Regular Expression)이란? **중요
- 문자열을 검색, 매칭, 치환 등을 처리하는 강력한!! 도구
- 특정 패턴을 문자열 내에서 찾아내는데 사용되며, 복잡한 문자열 검색과 처리를 효율적으로 할 수 있도록 함
- RegExp 객체를 사용하며 정규식을 다루며, 정규식 리터럴이나 생성자를 통해 생성

1. 정규식 생성 방법

- 리터럴 표기법
const regex = /pattern/flags; // flags는 사용 안할 땐 생략 가능

- 생성자 표기법
const regex = new RegExp('pattern', 'flags');
const regex = new RegExp('pattern'); // flags는 사용 안할 땐 생략 가능

2. 정규식 메서드
2.1 test()
- 정규식에 해당하는 패턴이 문자열에 포함되어 있는지 확인
- 결과는 true 또는 false

ex)
let regex = /website/;
console.log(regex.test(longSent));
regex = /weBsite/;
console.log(regex.test(longSent));

2.2 match()
- 문자열엥서 정규식과 일치하는 부분의 정보를 반환
- 반환되는 값을 플래그에 따라서 변경 됨

let regex = /name/;
console.log(longSent.match(regex));

2.3 replace()
- 문자열의 정규식과 일치하는 부분을 파라메터로 제공한 문자열로 치환한 문자열을 반환

let regex = /there/;
console.log(longSent.replace(regex, 'Everyone'));

2.4 search()
- 정규식과 일치하는 첫 번째 인덱스 반환

let regex = /My/;
console.log(longSent.search(regex)); // 14 -> My 앞 공백부터 세어줌

2.5 split()
- 정규식을 기준으로 문자열을 나누어 배열로 반환

let regex = / /;
console.log(longSent.split(regex)); // 공백을 기준으로 나누어 반환

2.6 exec()
- 매칭된 문자열이 포함된 배열을 반환 (match()와 같음)
- 배열에는 매치된 문자열의 시작 위치, 검색된 전체 문자열 포함 (match()와 같음)
- (match()와 다른점) g플래그나 y플래그가 있을 경우 검색 상태를 유지하고 반복 호출로 순차적 탐색

let regex = /website/;
console.log(regex.exec(longSent));

3. 플래그 **중요
- 정규식의 동작 방식을 제어하는 옵션
- 각 플래그는 특정 기능을 활성화하며, 여러 플래그를 조합하여 사용

3.1 g 플래그
- 전역 검색(global serch)
- 일치하는 패턴의 단어를 모두 반환 (배열 형태로 반환)

let regex = /name/g; // 문장의 모든 name 을 찾겠다
console.log(longSent.match(regex));

regex = /random/g;
console.log(longSent.match(regex));

3.2 i 플래그
- 대소문자를 구분하지 않음(case Insensitive)

let regex = /random/ig; // 여러 플래그 조합 가능
console.log(longSent.match(regex));

3.3 m 플래그
- 여러 줄 모드(Multiline)
- 줄바꿈을 기준으로 ^와 $를 각 줄에 대해 적용하도록 동작 방식을 확장
- 로그 분석, 줄 단위 데이터 처리 등에서 유용하게 사용

** 정규식의 경계에서 샘플 확인

3.4 s 플래그
- 줄바꿈 문자도 검색 가능
- .은 줄바꿈 문자를 제외한 모든 문자와 일치하지만, s 플래그를 사용하면 줄바꿈 문자도 포함하여 모든 문자와 일치

** 정규식 메타 문자에서 샘플 확인

3.5 u 플래그 (잘 사용하지 않음)
- 유니코드 모드(Unicode)
- javascript의 정규식 엔진은 2바이트 문자인 BMP 영역의 문자들만 제대로 처리
- 유니코드에서는 4바이트 문자도 존재하는데(ex.한글), 이들은 BMP 번위를 벗어난 문자
- 이모지나 고대 문자 등
- u 플래그는 유니코드 문자셋을 정확하게 처리
- 일반적인 유니코드 속성
  Letter: 문자 (예: \p{Letter})
  Uppercase_Letter: 대문자 문자 (예: \p{Uppercase_Letter})
  Lowercase_Letter: 소문자 문자 (예: \p{Lowercase_Letter})
  Titlecase_Letter: 타이틀 케이스 문자
  Other_Letter: 다른 유형의 문자
  Mark: 마크 문자 (조합 기호 등)
  Number: 숫자 문자
  Decimal_Number: 십진수 숫자
  Letter_Number: 문자로 표현된 숫자
  Other_Number: 다른 숫자 문자
  Punctuation: 구두점 문자
  Symbol: 기호 문자
  Other_Symbol: 기타 기호 문자
  Separator: 구분 기호 (예: 공백 문자)
  Emoji: 이모지 문자

let regex = /\p{Emoji}/g;
let text = '😀 Hello ❤ world 🌍 🧑‍🚀';
console.log(text.match(regex));
regex = /\p{Emoji}/ug;
console.log(text.match(regex));

3.6 y 플래그
- sticky 모드(현재 위치부터 검색)

let str = 'aabcabc';
let regex = /a/y;
console.log(regex.lastIndex); // 0
console.log(regex.exec(str)); // 첫번째 a 찾음 (순차적으로 탐색)
console.log(regex.lastIndex); // 1
console.log(regex.exec(str)); // 두번째 a 찾음
console.log(regex.lastIndex); // 2
console.log(regex.exec(str)); // null
console.log(regex.lastIndex); // 0

let regex = /a/;
console.log(regex.exec(str)); // 첫번째 a 찾음 (y 플래그가 없기 때문에 계속 첫번째 a만 찾음)
console.log(regex.lastIndex); // 0
console.log(regex.exec(str)); // 첫번째 a 찾음
console.log(regex.lastIndex); // 0

4. 정규식 메타문자
4.1  . 메타문자
- 임의의 한 문자 (s 플래그를 제외 시 줄바꿈 문자는 제외)
- /a.c/는 'abc', 'axc' 와 일치

let regex = /n..e/g;
console.log(longSent.match(regex));

let regex = /..ello/g;
console.log(longSent.match(regex)); // null

let regex = /..ello/gs;
console.log(longSent.match(regex)); // ['\nHello']

4.2 \d 메타문자
- 숫자 (0 - 9)

let regex = /\d\d\d\d/g;
console.log(longSent.match(regex));

4.3 \D 메타문자
- 숫자가 아닌 문자
- 띄어쓰기도 다 가져옴

let regex = /\D\D\D\D\D\D\D/g;
console.log(longSent.match(regex)); // ['\nHello ', 'there! ', 'My emai',]

4.4 \w 메타문자
- 단어 문자(알파벳, 숫자, _)
- 띄어쓰기, 특수문자는 가져오지 않음

let regex = /\w\w\w\w\w\w\w/g;
console.log(longSent.match(regex));

4.5 \W 메타문자
- 단어 문자가 아닌 문자
- /\W+/ "!@#"와 일치

let regex = /\W\W\W\W\W/g;
console.log(longSent.match(regex));

4.6 \s 메타문자
- 공백 문자(스페이스, 탭, 줄바꿈 등)

let regex = /\w\w\w\s/g; // 일반 문자 3개 뒤에 공백 문자 1개를 추출하라
console.log(longSent.match(regex));

4.7 \S 메타문자
- 줄바꿈 문자 또는 공백이 아닌 문자

let regex = /\S\S\S\S\S/g;
console.log(longSent.match(regex));

** 보통 소문자와 대문자는 반대되는 내용

5. 자바스크립트 정규식 수량자
5.1 * 수량자
- 0회 이상
- /a*/ 는 'aaa'. 'aaaaaa', '' 와 일치

let regex = /F.*o/g;
console.log(longSent.match(regex));

5.2 + 수량자
- 무조건 1회 이상 존재
- /a+/는 'aaa', 'aaaaaaa'와 일치, ''는 제외

let regex = /\s\w+\s/g;
console.log(longSent.match(regex));

let regex = /\s\w*\s/g;
console.log(longSent.match(regex));

5.3 ? 수량자
- 0회 또는 1회
- /a?b/는 'b', 'ab'와 일치

let regex = /com?/g;
console.log(longSent.match(regex));

5.4 {n} 수량자
- 정확히 n번 반복한 것을 검색
- /a{3}/는 'aaa'랑 일치

let regex = /\d{4}/g;
console.log(longSent.match(regex));

5.5 {n,} 수량자
- n번 이상 반복된 것을 검색
- /a{2,}/는 'aa'. 'aaaa' 2회 이상 반복되는 것과 일치

let regex = /\d{4,}/g;
console.log(longSent.match(regex));

5.6 {n,m} 수량자
- n번 이상 m번 이하
- /a{2,4}/ 'aa', 'aaa', 'aaaa'와 일치

let regex = /\d{1,3}/g;
console.log(longSent.match(regex));

6. 자바스크립트 경계
6.1 ^(시작문자) 경계
- 문자열의 시작을 의미
- /^hello/는 'hello world hello'의 처음 hello 와 일치

let regex = /^\[.+/g;  //시작이 대괄호[ 문자이고 뒤에 글자가 하나 이상인 것을 추출
console.log(longSent.match(regex)); // null

let regex = /^\[.+/gm; //줄바꿈 된 기준으로 시작이 대괄호[ 문자이고 뒤에 글자가 하나 이상인 것을 추출
console.log(longSent.match(regex)); // ["[2025-01-15 12:00:00] INFO: System started  "]

let logArr = longSent.match(regex); // 변수로 담아서 자세히 보기
for(let i = 0; i < logArr.length; i++){
  console.log(logArr[i]);
}

6.2 $ 경계
- 문자열의 끝을 의미
- /world$/는 'hello world world'의 마지막 world와 일치

let regex = /\w{3}\s*$/g; // 일반적 문자 3개뒤에 공백이 올수가 있는 문자
console.log(longSent.match(regex)); // null

let regex = /\w{3}\s*$/gm;
console.log(longSent.match(regex));

6.3 \b 경계 (잘 사용하지는 않음)
- 단어경계
- /\bhello\b/는 'hello'와 일치
- 특정 단어를 정확히 매칭하고 싶을 때 매우 유용

const text = 'cat category scatter';
console.log(text.match(/cat/g)); // ['cat', 'cat', 'cat']
console.log(text.match(/\bcat\b/g)); // ['cat']

6.4 \B 경계
- 단어 경계가 아님
- \Bhello/는 'ahello'와 일치

const text = 'cat category scatter';
console.log(text.match(/cat\B/g)); // cat뒤에 뭔가 이어져 있는 것 // ['cat', 'cat']

7. 특별한 메타 문자
7.1 [] 메타 문자
- 대괄호 안에 있는 문자들 중 하나와 일치
- - 문자를 사용해서 범위를 지정 ex) [a-z]는 소문자 알파벳과 일치
- 대괄호 내의 일부 문자는 특수한 의미를 가짐 ex) [^a-z]는 소문자 알파벳이 아닌 문자와 일치 -> ^는 시작 문자이지만 []안에서는 not을 의미

let regex = /[aeiou]/g;
console.log('hello world'.match(regex)); // ['e', 'o', 'o']

let regex = /[0-9]/g;
console.log('abc123'.match(regex)); // ['1', '2', '3']

let regex = /[0-9]+/g;
console.log('abc123'.match(regex)); // ['123']

let regex = /[^0-9]/g;
console.log('abc123'.match(regex)); // ['a', 'b', 'c']

let regex = /[^0-9]+/g;
console.log('abc123'.match(regex)); // ['abc']

let regex = /[0-9a-z]+/g;
console.log('abc123'.match(regex)); // null

7.2 () 메타 문자
- 소괄호는 하위 표현식을 그룹화하여 하나의 단위로 취급
- 일치하는 문자열을 캡쳐하여 나중에 사용
- 캡쳐되지 않는 그룹은 (?:) 으로 표시

let phone = '010-1234-5678';
let regex = /\d{3}-\d{4}-\d{4}/; // ['010-1234-5678', index: 0, input: '010-1234-5678', groups: undefined]
console.log(phone.match(regex));

let regex = /(\d{3})-(\d{4})-(\d{4})/;
console.log(phone.match(regex)); // ['010-1234-5678', '010', '1234', '5678', index: 0, input: '010-1234-5678', groups: undefined]
console.log(phone.match(regex)[1]); // 010

let formatted = phone.replace(regex, '$3-$2-$1');
console.log(formatted); // 5678-1234-010
let formatted = phone.replace(regex, '$1-$2-$3');
console.log(formatted); // 010-1234-5678

------
let phone = '010-1234-5678';
let regex = /(\d{3})-(\d{4})-(\d{4})/;
let match = phone.match(regex);
if(match){
  let areaCode = match[1];
  let mainNumber = `${match[2]}-${match[3]}`;
  console.log(areaCode, mainNumber);
}

// 분석해보기
이메일 정규식
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

728x90

'자바스크립트 > ⚪️ Vanilla' 카테고리의 다른 글

통신 JSON  (0) 2025.02.26
정규표현식  (0) 2025.02.26
이벤트 핸들러  (0) 2025.01.18
[js] 이벤트 리스너  (0) 2025.01.14
[js] 이벤트 핸들러  (0) 2025.01.12
Comments