program tip

JavaScript에 왜 null 값이 있습니까?

radiobox 2020. 7. 29. 08:04
반응형

JavaScript에 왜 null 값이 있습니까?


- 자바 스크립트에서 기본적으로 '나는 존재하지 않는'라고 두 개의 값이있는 undefinednull.

프로그래머가 아무것도 할 것이다 할당되지 않은에 속성 undefined이 될 수있는 속성에 대해,하지만 순서는 null, null명시 적으로 할당해야합니다.

한 번은 기본 가치와 대상 null이기 때문에 필요가 있다고 생각했습니다 . 이 경우에도 아니다 얻을 것입니다 - 수단도 사실, 모두 기본 값은 다음과 같습니다 모두 빈 객체로 변환 될 것이다 (한 생성자에서 선포 장애에 대한 오류가 발생한다), 생성자 함수에서 반환 할 수 있습니다.undefinednulltypeof null'object'undefinednull

또한 false부울 컨텍스트에서 평가 됩니다. 내가 생각할 수있는 유일한 차이점은 하나는로 평가 NaN하고 다른 하나 0는 숫자로 평가한다는 것입니다 .

그렇다면 왜 둘 다 undefined있고 null이것이 null속성이 설정되었는지 여부를 찾으려고 할 때 잘못 확인하는 프로그래머를 혼란스럽게 만드는 이유는 무엇입니까?

내가 알고 싶은 것은 누군가가 대신 사용해야 null할 수없는 합리적인 예가 있다면 사용할 수 없다는 undefined것입니다.

따라서 일반적인 합의는 undefined'그러한 재산이 없음'을 null의미 하는 반면 '재산이 존재하지만 가치가 없음 '을 의미합니다.

JavaScript 구현이 실제로이 동작을 강제 할 undefined경우 완벽하게 유효한 기본 값이므로 기존 속성에 쉽게 할당하여이 계약을 위반할 수 있습니다. 따라서 속성이 존재하는지 확인하려면 in연산자 를 사용해야 hasOwnProperty()합니다. 다시 한 번 : undefined와에 대한 개별 값에 대한 실제 사용은 null무엇입니까?

undefined더 이상 사용하지 않지만 원하지 않는 속성 값을 설정 해제하려고 할 때 실제로 사용 합니다 delete. null대신 사용해야합니까 ?


문제는 실제로 "JS에 null 값이있는 이유"가 아닙니다. 대부분의 언어에는 일종의 null 값이 있으며 일반적으로 매우 유용한 것으로 간주됩니다.

문제는 " JS에 정의되지 않은이있는 이유 "입니다. 사용되는 주요 장소 :

  1. 'var x;'를 선언 할 때 그러나 할당하지 않으면 x는 정의되지 않습니다.
  2. 함수가 선언하는 것보다 적은 수의 인수를 얻는 경우;
  3. 존재하지 않는 객체 속성에 액세스 할 때

'null'은 확실히 (1)과 (2) *에서도 잘 작동했을 것입니다. (3) 실제로 예외를 바로 버려야하며 나중에 실패 할 이상한 '정의되지 않은'을 반환하지 않는 것이 디버깅 어려움의 큰 원인입니다.

* : (2) 예외를 던져야한다고 주장 할 수도 있지만 기본 / 변수 인수에 대해보다 명확하고 명확한 메커니즘을 제공해야합니다.

그러나 JavaScript에는 원래 예외가 없었거나 객체에 특정 이름의 멤버가 있는지 물어볼 수있는 방법이 없었습니다. 유일한 방법은 멤버에 액세스하여 얻는 내용을 보는 것입니다. 'null'은 이미 목적이 있고 멤버를 설정하려는 경우 다른 대역 외 값이 필요했습니다. 따라서 우리는 '정의되지 않음'을 가지고 있으며, 지적한대로 문제가 있으며, 우리가 결코 제거 할 수없는 또 다른 훌륭한 JavaScript 기능입니다.

더 이상 사용하지 않지만 삭제하고 싶지 않은 속성 값을 설정 해제하려는 경우 실제로 undefined를 사용합니다. 대신 null을 사용해야합니까?

예. 다른 언어가 대신 예외를 throw 할 수있을 때 신호를 보내려면 '정의되지 않음'을 특수한 값으로 유지하십시오.

'null'로 설정하면 오류가 발생할 수있는 일부 IE DOM 인터페이스를 제외하고 'null'이 일반적으로 더 좋습니다. 이 경우 빈 문자열로 설정하는 것이 종종 작동합니다.


여기에 가장 잘 설명 되어 있지만 요약하면 다음과 같습니다.

undefined는 유형과 값이없고 null은 값이 없다는 것입니다.

또한 간단한 '=='비교를 수행하는 경우 맞습니다. 그러나 ===를 시도하면 유형과 값을 모두 비교할 수 있으며 그 차이를 알 수 있습니다.


적어도 자바 스크립트에서는 많은 사람들이 제안한 유일한 이유 ( " 이러한 변수 / 속성이 없음 "을 의미 함)가 유효하지 않기 때문에 null와를 모두 가질 이유가 없다고 생각 합니다. 변수 / 속성이 존재하는지 여부를 알 수 없습니다.undefinedundefinedundefined

console.log(foo);               // "ReferenceError: foo is not defined"
                                // foo does not exist
var foo;
console.log(foo);               // "undefined", a different response
console.log(foo === undefined); // "true", but it does exist

var obj = {};
console.log(obj.hasOwnProperty("foo")); // "false", no such property
obj.foo = undefined;
console.log(obj.hasOwnProperty("foo")); // "true", it exists and has the value "undefined"
console.log(obj.foo === undefined);     // "true", but it does exist

obj.bar = "delete me";
obj.bar = undefined;
console.log(obj.hasOwnProperty("bar")); // "true", not actually deleted
delete obj.bar;
console.log(obj.hasOwnProperty("bar")); // "false", deleted

보시다시피, 검사 foo === undefinedfoo존재 여부를 알려주지 obj.bar = undefined않으며 설정 은 실제로 삭제되지 않습니다 bar.

undefined"존재하지 않음"을 나타내는 JavaScript 작성자의 원래 의도 일 수 있습니다 . 그러나 구현 방식은 그렇지 않았습니다.


둘 다 필요로하는 것은 전적으로 가능합니다. 예를 들어 WMI를 쿼리하면 null 값을 가진 클래스 반환 속성을 가질 수 있습니다. 그것들은 정의되어 있으며, 당시에는 null을 유지합니다.


JavaScript undefined가 "그런 속성이 없다"고 null"속성이 없다"는 결론 은 완벽하다고 생각합니다. 그리고 JavaScript와 같이 동적 인 언어에서는 매우 중요한 차이점입니다. 오리 타이핑을 사용한다는 것은 존재하지 않는 속성과 가치가없는 속성을 구별 할 수 있어야한다는 것을 의미합니다. 유형 정보를 도출하는 주요 수단입니다. 정적으로 유형이 지정된 언어에서는 필드가 null 인 필드와 존재하지 않는 필드 사이에 명확한 차이가 있습니다. JavaScript에서 이것은 다르지 않습니다. 그러나 런타임시 점검되며 그 때까지 수정할 수 있습니다.

구별이 흐려짐에 따라 구현이 이상하다는 데 동의해야합니다. 그러나 JavaScript에서는 구별이 중요하다고 생각합니다. 그리고 할당 할 수 있어야합니다 undefined.

JavaScript로 작성된 온라인 RPG에 대해 얼마 전에 블로그 게시물을 읽은 것을 기억합니다. 프로토 타입 (클래스, 함수 등)이 아닌 기존 인스턴스의 복사본으로 객체를 만든 다음 변경 한 예제를 사용했습니다. 이를 통해 undefined기존 객체를 수정할 때 얼마나 강력한 지 알 수 있었지만 누가 쓴 사람인지는 기억 나지 않습니다.


의미 적으로 그들은 다른 것을 의미합니다. null 유형은 도메인에 정확히 하나의 값을 가지며, null 및 속성에이 특정 값이 할당 될 수 있습니다. 정의되지 않음은 값이 지정되지 않았 음을 나타냅니다.


As a Java programmer, I see a huge difference between undefined and null. Coding JavaScript, not so much, because JavaScript is not strongly typed, and the differences between undefined and null are blurred by the automatic conversions that are frequently performed by run-time. BTW, I take frequent advantage of those conversions; they make my JS code more compact and readable.

To answer your question, undefined means that a value was never set. Practically speaking, this generally points to a bug. If yourObject.property is undefined, that means you didn't set the property for some reason, or I'm looking for something that doesn't exist at all. This is a real issue when working on a project with more than one coder.

null means that "no value" was explicitly set. Practically speaking, you are telling me something about the property, perhaps that it isn't used in this context, or that a value has yet to be determined.

In Java, attempts to access a field that is undefined will always result in an exception. In fact, the compiler can be made to warn you about this in your code.


Try this example:

<html>
<head>
    <script type="text/javascript">
        function ShowObjProperties(obj) {
            var property, propCollection = "";

            for(property in obj) {
                propCollection += (property + ": " + obj[property] + "\n");
            }

            alert(propCollection);
        }

        var obj = {
            userid: 3,
            name: 'me!',
            speak: function() { alert('Hi! My name is ' + this.name + ' and my ID is ' + this.userid + '.'); }
        }

        //Shows all properties
        ShowObjProperties(obj);

        //The Speak function is no longer in the list!
        delete obj.speak;
        alert(typeof obj.speak);
        ShowObjProperties(obj);

        //The UserID is still listed, it just has no value!
        obj.userid = null;
        ShowObjProperties(obj);
    </script>
</head>
<body>

</body>
</html>

I think that there is a very real use for 2 different types here.


What it comes down to is javascripts dynamic nature.

Things may be undefined so that they can be added at a later point. This is arguably why javascript is so powerful and extensible.


it's an important language feature if you wrap your program around the evented paradigm of javascript.

// a key exists as a placeholder for something
if(obj[name] === null) 
// no key exists int eh hashtable that is in this object
if(obj[name] === undefined)

this is very useful if you are dealing with a set of data that needs a value to represent 'nothing' to indicate some action different from using 'nothing' to indicate the default action.

filter_func_pt = {
  date:function(d){ return Math.round(d.getTime()/1000);},
  user: null,
}

function transform(obj){
    var ret = {};
    for( var prop in obj){
       var f = filter_func_pt[prop];
       if(f)
          ret[prop] = f(obj);
       else if(filter_func_pt[prop] === null)
         continue;
       else
         ret[prop] == obj;
    }
  return ret;
}

var a = {
   date: new Date(),
   user: 'sam'
   votes: [23, 41, 55] 
};

var b = transform(a);

/* b = {
 *    date: 1298582417
 *    votes: [23, 41, 55]
 * }
 */

in the above code the null keyword and the undefined server very clear and different purposes. the lookup that is not found in the filter_func_pt object which returns undefined means to add the property to the return object as is, whereas a null value indicates that the value should be withheld, and not added, and the presence of any true value in this case represents a function used to transform the value before adding it to the ret object.


null is beautiful

as are all other Types of Live Script.

cite: In JavaScript, there are two values which basically say 'I don't exist' - undefined and null.

Why would you want to say incorrect things?!

"null" is "empty Object" just like "0" is an "empty Number". 0, is nothing -yet it exists as a Type of a Number thing. null is of course also empty but "it is" and it's a well defined thing of an Object Type.

It common to speak of these thing as of "types", when they are not. In fact they are "categories". But that's over now.

So will stick to it to say that "null" is a Type of Object without a Kind. And "null" says "I very much exist[!], but I don't have content of my kind".

Whereas undefined lacks both the Type and the Kind where undefined happens to also be its Type definition. An undefined type of a type becomes its distinctive typology. A sort of a [does "nothing" exist and how do you define "nothing"?] question.

cite: undefined nor null can be returned from a constructor function, as both will be converter to an empty object

You've managed to once again say an incorrect thing. Of course not, the "undefined" is not an Object, its a plain Token which we humans understand; but contrary to that null is - and it's telling you that: its Type is correct, but the Kind you are looking for is not contained within it, or at least -not at this time. Come visit us later when we put\assign some object in\to it.

cite: The only real difference I can think of is that one evaluates to NaN, the other to 0 in numeric contexts.

That makes the whole point of their core distinction, as mentioned: undefined is a plain token and since it is made up of the same 'genetic' material as its distant relatives: strings, the [ +undefined ] operation will duck-convert it to NaN, similarly null will of course morph itself into a correct kind 0 \Number instead, and as opposed to undefined that will morph into a string (!which is not empty!) and that's exactly why it yields NaN instead. Where: +undefined >> +"undefined" >> NaN. Since numeric context expects explicit value.

While the Boolean context expects reference - finds nothing to convert and yields 'false'.

Let's cut through now...

cite: So once again: what's the practical use for seperate values for undefined and null?

I will try to give you only two empirical examples and hope to suffice

oElement.onclick >> null

//means -the property exists; its expected value is of Type: Object, and that oElement supports the "onclick" event!

oElement.innerText >> ""

//means - the property exists; its expected value is of Type: String, which means that oElement supports the "innerText" property.

on both cases -if you receive "undefined" it means that the property doesn't exist; is not supported or has a wrong (ua vendor) implementation.

Stay frost and have fun.


after reading amazing discussion regarding undefined vs null, little search on google took me to Mozilla Documentations https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null it is mentioned - null is often retrieved in a place where an object can be expected but no object is relevant.

Isn't is similar to Null object pattern https://en.wikipedia.org/wiki/Null_object_pattern

So i guess this make sense to have Null data type.

Documentation also mentioned as typeof null // "object" (not "null" for legacy reasons)

Not sure what legacy reasons are

참고URL : https://stackoverflow.com/questions/461966/why-is-there-a-null-value-in-javascript

반응형