간단한 javascript 기초 개념 정리 (1)

이승민·2020년 4월 27일
0

1. const의 의미

const의 경우 var, let 과 같이 변수를 선언할때 사용되는 방식이다.
다만 var, let과 다른 점은 const를 통해 한번 변수가 선언되면 재할당이 불가능하다는 것이다.

<예시>

// var의 경우 한번 선언된 변수의 재할당이 가능하다.

var a = "b";
a = "b"

var a = "c";
a = "c"

// const의 경우 한번 선언된 변수의 재할당이 불가능하다.

const a = "b";
a = "b"

const a = c
console.log (a) // Uncaught SyntaxError: Identifier 'a' has already been declared 에러 발생

코드가 길어질 수록 변수의 재할당이 가능한 var 방식의 위험성 또한 커지기 때문에 const를 통해 변수를 선언하는 것이 예기치 못한 문제를 예방하는 방법 중 하나라고 볼 수 있다.

2. Element 객체를 javascript로 가져오는 방법

Elemtnt 객체를 javascript로 가져오는 방법은 다양하다.

  1. document.querySelector(); -> id, class, tag 등 다양한 selector (선택자) 를 이용하여 가장 첫번째에 위치한 Element 객채를 가져올 수 있다.
    ( ) 안에 검색할 선택자를 입력하는데 각각의 입력 방식은 css에서의 입력 방식과 동일하다.
    querySelectorAll(); 을 사용하면 해당 선택자와 일치하는 Element 객체의 모든 리스트를 가져온다.

<예시>

const title = document.querySelector('#title'); // id
const title = document.querySelector('.title'); // class
const title = document.querySelector('title'); // tag name

이러한 방식으로 가져와 변수를 선언한 Element 객채를 querySelector 앞에 입력하여 하위 Element 객체를 가져올 수 있다.
<예시>

const title = document.querySelector('#title'),
text = title.querySelector ('h1');
  1. document.getElementById(); -> id를 통하여 하위 Element 객체를 가져올 수 있다.

<예시>

const title = document.getElementById('title');
  1. document.getElementClassName(); -> class를 통하여 하위 Element 객체를 가져올 수 있다.

<예시>

const title = document.getElementByClassName('title');
  1. document.getElementTagName(); -> tag를 통하여 하위 Element 객체를 가져올 수 있다.

<예시>

const title = document.getElementByTagName('p');
const text = document.getElementByTagName('h1');

3. 삼항 조건 연산자 (Conditional operator)

조건문을 if, else를 사용하지 않고 한줄로 작성할 수 있는 방법
<예시>

// number가 10보다 작을때는 number 앞에 0을 붙혀서 출력하고 그렇지 않을 때는 number 값만 출력한다.

`${number < 10 ? `0${number}` : number}`;
profile
프론트 앤드 개발자를 꿈꿉니다.

0개의 댓글