[JavaScript] 기초_변수와 타입

Seungmin Lee·2022년 6월 24일
0

JavaScript

목록 보기
1/14
post-thumbnail

1. 변수

1-1. 변수의 선언과 할당

변수 선언은 데이터의 보관함을 만든 것이라고 할 수 있고 그 데이터의 보관함의 이름이 변수인 것이다. 그리고 변수에 값을 할당해주는 것은 보관함에 데이터를 저장한 것으로 생각해볼 수 있다.

1-2. 변수 선언 방식

변수의 선언 방식 : var, let, const
var은 재선언이 가능하지만 letconst는 재선언 할 수 없다. letconst의 차이는 재할당 여부이다. let은 재할당이 가능하지만 const는 재할당 또한 불가능하다.

var

var은 재선언이 가능하기 때문에 에러 없이 다른 값이 출력된다.

var fruit = 'apple'
console.log(fruit) // 'apple'

var fruit = 'banana'
console.log(fruit) // 'banana'

편리하게 사용할 수는 있으나 프로젝트가 커질 수록 어디에 어떤 변수를 사용했는지 파악이 어렵고 변경될 우려가 있는 단점을 갖고 있다.

let

let은 재선언할 수 없기 때문에 이미 선언되었다는 에러가 뜨게 된다. 하지만 재할당은 가능하기 때문에 에러 없이 재할당한 값으로 출력되는 것을 볼 수 있다.

let fruit = 'apple'
console.log(fruit) // 'apple'

let fruit = 'banana'
console.log(fruit) //Uncaught SyntaxError: Identifier 'fruit' has already been declared

fruit = 'orange'
console.log(fruit) // 'orange'

const

const는 재선언, 재할당 모두 불가능하다.

const fruit = 'apple'
console.log(fruit); // 'apple'

const fruit = 'banana'
console.log(fruit) //Uncaught SyntaxError: Identifier 'fruit' has already been declared

fruit = 'orange'
console.log(fruit) // Uncaught TypeError: Assignment to constant variable

하지만 객체의 속성(property) 변경은 가능하다.

const obj = { bar : 1, baz : 2 }
obj.bar = 3;
console.log(obj.bar) // 3

2. type

typeof

JavaScript의 변수에 할당하는 값에는 type이 있다. type에는 숫자(Number), 문자(String), true/false(Boolean), 객체, undefined(변수에 값을 할당하지 않음), 함수(변수에 함수를 할당), Null 등이 있다.

typeof 연산자를 이용해서 값의 타입을 확인할 수 있다.

console.log(typeof '1') // 'string'
console.log(typeof 1) // 'number'
console.log(typeof (1 < 2)) // 'boolean'
let test;
console.log(typeof test) // undefined
function typeTest(){};
let test = typeTest;
console.log(typeof test) // 'function'
let array = ['sm', 30]
console.log(typeof array) // 'object'

let object = {name:'sm', age:30}
console.log(typeof object) // 'object'
profile
<Profile name="seungmin" role="frontendDeveloper" />

0개의 댓글