TIL 1. JS - 변수와 데이터 타입

문승준·2021년 7월 26일
3

JavaScript

목록 보기
6/8
post-thumbnail

변수 (Variable)

  • 변수란 데이터를 담을 수 있는 대상, 컨테이너이다.
  • 숫자,문자뿐 아니라 복잡한 데이터부터 함수까지 모조리 담을 수 있다

1. 변수 선언과 할당 (Declare, Initialize, Assign)

  • 변수선언과 할당은 별개다.
let myTest = '100'; // myTest라는 변수를 선언하고 100의 값을 할당한다.
let myPower = myTest; // 그리고 myTest를 변수 myPower의 값으로 할당한다.
  • 선언만 했을때? 그 자체로는 값을 가지지 않는다.
let myTest;
console.log(myTest) //undefined
  • 선언했으면 다시 할 필요없이 값을 할당 가능하다.
let myTest;
myTest = 100;

2. 변수이름 정하기 (Naming rules)

  • 대소문자를 구분한다.

  • 알파벳, 숫자, $, (언더스코어) 사용 가능하다. (단, 숫자나 _로 시작하지 말자)

  • camelCase

3. var, let, const의 차이점

  • var 는 변수 재선언이 가능해서, 복잡한 코드에서는 헷갈린다.
var myName = 'billy';
console.log(myName) // 'billy'

var myName = 'peter';
console.log(myName) // 'peter'
  • let 은 변수 재선언이 불가하지만, 재할당은 가능하다.
let myName = 'billy';
console.log(myName) // 'billy'

let myName = 'peter';
console.log(myName) // Uncaught SyntaxError: Identifier 'myName' has already been declared

myName = 'john';
console.log(myName) // 'john'
  • const 는 변수 재선언이 불가하고, 재할당도 불가하다.
const myName = 'billy';
console.log(myName) // 'billy'

const myName = 'peter';
console.log(myName) // Uncaught SyntaxError: Identifier 'myName' has already been declared

myName = 'john';
console.log(myName) // Uncaught TypeError: Assignment to constant variable.

자바스크립트는 ES6에서 도입된 let, const를 포함하여 모든 선언(var, let, const, function, function*, class)을 호이스팅한다. 호이스팅(hoisting)에 관해서는 나중에 더 자세히 알아보자 🤔


데이터 타입 (Data Type)

  • 변수에 저장할 수 있는 데이터 타입들.
  • 다양한 연산자를 활용할 수 있다.

1. 기본타입 (Primitive type)

  • Number (+ - * / %)
let myInteger = 100;
let myFloat = 0.35;
console.log(typeof myInteger, typeof myFloat) // number number

//Number() 메서드 - string을 number로
let x = '10';
let num = Number(x);
console.log(num + 10) // 20 (true는 1, false는 2를 리턴한다.)

//toString() 메서드 - number를 string으로
let x = 10;
let num = x.toString();
console.log(num) // '10'

let x = 10;
let num = x.toString(2); //parameter n진법으로 표현
console.log(num) // '1010'

//parseInt(), parseFloat() 메서드 - 정수, 실수
let x = '7 day';
let num = parseInt(x);
console.log(num) // 7 (string으로 시작하면 NaN)

let x = '4.3 2.1';
let num = parseFloat(x);
console.log(num) // 4.3 (string으로 시작하면 NaN)

  • String
let firstName = 'Seungjun'
let lastName = 'Moon';
let myName = firstName + lastName;
console.log(myName) // 'SeungjunMoon'
console.log(myName.length) // 12
console.log(10 + 23 + myName) // '33SeungjunMoon' <-string이 된다

//concat() - 문자열과 인자를 합친다
console.log('pizza'.concat('-lover')); // 'pizza-lover'

//trim() - 문자열 앞뒤 빈칸을 제거한다
console.log('  alone  '.trim()); // 'alone'

//slice() - 시작부터 종료이전까지 잘라낸다
console.log('world'.slice(0,4)); // 'worl' (-1은 오른쪽 끝부터)

//split() - 주어진 문자를 기준으로 구분한 배열을 반환한다
console.log( '1.2.3'.split('.') ); // ['1', '2', '3']
  • Boolean
let test = 3 < 4 ;
console.log(test) // true
console.log(typeof test) // boolean
  • undefined
let myThing;
console.log(myThing) // undefined
console.log(typeof myThing) // undefined
  • null
let myThing = null;
console.log(myThing) // null
console.log(typeof myThing) // object <- null은 object 타입이다.

console.log(null == undefined);   // true <- value는 같다.
console.log(null === undefined);  // false <- type은 다르다.

2. 참조타입 (Reference type)

  • array
let myArray = [23, 'pizza', true];
console.log(myArray[1]) // pizza
  • object
let myObject = {name: 'billy', likesPizza: true};
console.log(myObject.name) // billy
  • function
function myFunction () {
  let name = 'danny moon'
  console.log(name)
  return name
}

myFunction();

typeof 연산자의 원리나 undefined, null, NaN의 차이에 대해 나중에 더 알아보자 🤔

profile
개발자가 될 팔자

0개의 댓글