새소식

반응형
WEB/JavaScript

[JavaScript] JS Boolean Value에 대하여 알아보기.

  • -
반응형

2021-04-08


Photo by Michiel Annaert on Unsplash

흔히 [참 거짓] / [true false]를 나누어야 하는 경우가 다수 존재한다. 이럴 경우를 대비하여 js 내부에 만들어진 Value가 Boolean이다. 이 Boolean을 이용하는 방법을 알아보자.


- Boolean(x ? y)

 

두 가지의 값(데이터)을 비교하여 같은지 다른지를 비교하기 위해서 부등호를 사용하게 된다. Boolean에서 사용할 수 있는 부등호는 [ == , > , < , >= , <= ] 다섯 가지가 존재한다. 아래의 예제를 보자.

(추가적으로!= 부등호 표현이 있다. 이는 좌변가 우변이 같지 않으면 true를 리턴한다.)

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript"> 
	

	console.log(Boolean(1 == 1)) // true 같음 
	console.log(Boolean(1 > 1)) // false 같음 	
	console.log(Boolean(2 > 1)) // true 좌변이 큼
	console.log(Boolean(2 < 3)) // true 우변이 큼	
	console.log(Boolean(1 >= 1)) // true 좌변이 같거나 좌변이 큼
	console.log(Boolean(2 >= 1)) // true 좌변이 같거나 좌변이 큼
	console.log(Boolean(1 >= 2)) // false 자변이 더 작음 

	
</script>
</head>
<body>
Hello World

</body>
</html>​

 

이와 같이 조건에 따른 true/false바로 확인하는 방법으로는 Boolean타입에 소괄호를 준 뒤 부등호로 두 값(데이터)을 비교해보면 손쉽게 확인할 수 있다.


- Boolean (변수)

 

단순 숫자 / 문자뿐 아니라 직접적인 변수들간의 비교도 가능하다.  아래의 예제들을 살펴보자.

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript"> 
	var x = "Hi"
	var y = "hi"

	console.log(Boolean(x == y)) // false 
</script>
</head>
<body>
Hello World

</body>
</html>​

 

Boolean 타입은 대소문자를 구분하기 때문에 같은 내용의 문자라도 대소문자가 다르면 false를 리턴한다.


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript"> 
	
	var x = false
	var y = new Boolean(false)

	console.log(Boolean(x == y)) // true 
</script>
</head>
<body>
Hello World

</body>
</html>​

 

새로운 객체를 생성하여 false를 대입하든 직접 false를 대입하던 두 변수들 같은 값을 가지고 있기 때문에 true를 리턴한다.


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript"> 
	
	var x = 10
	var y = new Number(10)

	console.log(Boolean(x == y)) // true 
</script>
</head>
<body>
Hello World

</body>
</html>​

 

다른 타입도 마찬가지로 내부의 값(데이터)만 같으면 true를 반환한다.


메인 이미치 출처: Photo by Michiel Annaert on Unsplash  

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.