본문 바로가기

기술

[Javascript] 기초: 주석, 자료형, 변수선언, 문자열 포멧팅, If문, Switch문, 논리연산자

이 글은 다른 언어를 접한 경험은 있지만, 자바스크립트는 처음 입문하시는 분들을 위한 글입니다.

주석

Single-line 주석

// single line comment

Multi-line 주석

/*
multi-line comments
*/

자료형

1. Number: 소수를 포함한 숫자 - ``4``, ``24.56``

2. String: 문자열 집합 - ``' ... '``, ``" ... "``

3. Boolean: 불린형 - ``true``, ``false``

4. Null: 데이터가 없음을 나타내는 자료형 - ``null``

5. Undefined: 데이터 타입이 지정되지 않음을 나타내는 자료형 - ``undefined``

6. Symbol: 고유 식별자

7. Object: 여러 자료들의 집합

*🤟Note
*
null vs undefined

[

undefined와 null의 차이점

undefined vs null 이 두 타입은 모두 자바스크립트에서 '값이 없음'을 나타냅니다. 기본적으로 값이 할당되지 않은 변수는 undefined 타입이며, undefined 타입은 변수 자체의 값 또한 undefined 입니다. 즉, 정..

webclub.tistory.com

](https://webclub.tistory.com/1)

콘솔에 출력

console.log('hello world');

Properties

Object에는 프로퍼티가 존재한다. (class의 필드값과 비슷한 것 같다.) 다음 예시를 보자.

// String 프로퍼티 length
console.log('Hello'.length); // Prints 5

Method

Object에는 실행할 수 있는 메소드가 존재한다. 다음 예시를 보자.

// String 메소드 toUpperCase()
console.log('Hello'.toUpperCase()); // Prints hello

변수 선언

ES5: var로 모든 변수 선언

var myName = 'Seonkyu';

ES6: let과 const로 변수 선언

_let_은 변수에 할당된 값 변경 가능. 또한 값의 할당을 나중에 할 수도 있다.

let myName;
console.log(myName);    // Output: undefined
myName = 'Seonkyu';
console.log(myName);    // Output: Seonkyu

_const_는 변수에 할당된 값 변경 불가능. 또한 선언과 동시에 값을 할당해야 한다.

const myName = 'Seonkyu';
console.log(myName);    // Output: Seonkyu

문자열 포멧팅

ES6에 들어오면서 template literals를 사용할 수 있다.

const myName = 'Seonkyu';
console.log(`My name is ${myName}.`);    // Output: My name is Seonkyu.

If 문

if (true) {
    console.log('True');
} else if (false) {
    console.log('False');
} else {
    console.log('Equal');
}

거짓으로 분류되는 것

- ``0``

- ``""`` or ``''``

- ``null``

- ``undefined``

- ``NaN``

Switch 문

let count = 3;

switch (age) {
    case 1 :
       console.log(1);
       break;
    case 2 :
       console.log(2);
       break;
    default: 
        console.log('greater than 2');
        break;
}

논리연산자

- and: ``&&``

- or: ``||``

- not: ``!``

🤟Note

다음과 같이 ``||`` 왼쪽 변수가 거짓으로 판별될 경우 디폴트로 오른쪽 값을 대입하는 short-circuit evaluation을 사용할 수 있다.

let username;
let defaultName = username || 'Stranger';
console.log(defaultName)    // Output: Stranger

삼항 조건 연산자

(expression) ? console.log('True') : console.log('False');