null || undefined

손정만·2022년 2월 14일
0

nullundefinend 의 차이

undefined 와 null은 같은가

javascript 에선 변수를 선언만 했을경우 undefined 로 정의된다.
값이 정의되지 않았음을 의미 한다. null은 값이 존재하지 않음을 의미한다.

둘 다 비슷하다고 볼수 있으나 다르다.
둘의 차이를 간과하여 초기화의 의미로써 undefined 를 사용했으나
이제서야 알아보고 null 을 사용 하고자 한다.

const u = undefined;
const n = null;

console.log(u, n); // undefined, null
console.log(u == n, u === n); // true, false
console.log(typeof u, typeof n); // undefined, object

위와 같이 간단히 테스트 해보았을때, 두 값은 다르지 않은것을 확인할 수 있다.
심지어 nullobject로 선언되어있다.
왜일까? 그렇게 정의 되었기 때문이라고 한다..

그렇다면 이 두 값이 어떻게 다른것일까

const object = {};
console.log(object.u, object.n); // undefined undefined
console.log(object.hasOwnProperty('u')); // false
console.log(object.hasOwnProperty('n')); // false

object.u = undefined;
object.n = null;
console.log(object.u, object.n); // undefined null
console.log(object.hasOwnProperty('u')); // true
console.log(object.hasOwnProperty('n')); // true
console.log(object); // {u: undefined, n: null}

delete object.u;
delete object.n;
console.log(object.u, object.n); // undefined undefined
console.log(object.hasOwnProperty('u')); // false
console.log(object.hasOwnProperty('n')); // false
console.log(object); // {}

undefined 로 정의 되었을때, 실제 object 안에선 해당하는 하위 값으로 존재하지만
undefined이기에 목적을 가지고 정의된것인지, 정의가 되지 않은것인지 불명확해진다.

나또한 일부 데이터를 넘겨받을때나 옵션을 설정할때 정의되었는가에 대해

typeof target === 'undefined' 

이런 형태로 값의 할당여부를 확인하기 때문에
객체가 할당되지 않은건 null 을 이용하는것이 맞다고 본다

참조

https://stackoverflow.com/questions/5076944/what-is-the-difference-between-null-and-undefined-in-javascript
https://stackoverflow.com/questions/461966/why-is-there-a-null-value-in-javascript

0개의 댓글