본문 바로가기

StackOverflow

[Javascript] !-- 연산자가 무슨 뜻인가요?

http://stackoverflow.com/questions/34323527/what-does-do-in-javascript


Q: 자바스크립트에서,  !-- 연산자가 무슨 뜻인가요?

아래와 같은 코드를 발견했습니다. (이 질문에서 가져왔습니다)

var walk = function(dir, done) {
    var results = [];

    fs.readdir(dir, function(err, list) {
        if (err)
            return done(err);

        var pending = list.length;

        if (!pending) 
            return done(null, results);

        list.forEach(function(file) {
            file = path.resolve(dir, file);
            fs.stat(file, function(err, stat) {
                if (stat && stat.isDirectory()) {
                    walk(file, function(err, res) {
                        results = results.concat(res);

                        if (!--pending)
                            done(null, results);
                    });
                } else {
                    results.push(file);

                    if (!--pending) 
                        done(null, results);
                }
            });
        });
    });
};

이 코드를 읽으려고 시도했는데, !--pending 부분만 빼고는 대략 알 것 같습니다. 이 코드에서, 이 명령이 하는 역할이 무엇인가요?

수정: 모든 코멘트에 감사드립니다. 그렇지만 답변을 이미 여러 번 받았습니다. 어쨌든 감사합니다!

(질문자: Kieran E)

댓글: 이건 다른 사람이 코드를 유지보수하지 못하게 만드는 아주 적절한 방법입니다.  Eric J

댓글: !~--[value] ^ true 저는 이걸 "작업 보안" 이라고 부르겠습니다. TbWill4321



A: ! 연산자는 boolean 타입에서, 반대의 결과를 만들어냅니다.

!true == false
!false == true
!1 == false
!0 == true

--[value]는 숫자 1을 해당 변수에서 뺀 뒤 반환합니다.

var a = 1, b = 2;
--a == 0
--b == 1

즉, !--pending은 변수 pending에서 숫자 1을 뺀 뒤, 그것을 boolean 형식으로 보았을 때 true인지 false인지를 판단하여 그 반대를 리턴합니다. (숫자 0이 아니면 true 입니다)

pending = 2; !--pending == false 
pending = 1; !--pending == true
pending = 0; !--pending == false

그리고, ProTip을 따르세요. 이것은 다른 프로그래밍에도 적용되는 격언인데, 가장 선언적인 (declarative) 언어인 자바스크립트에서, 이건 외계인 같은 코드입니다.

(답변자: TbWill4321)

댓글: ProTip: 이런거 하지 마세요. 이건 제정신이 아닌 짓입니다.  Naftuli Tzvi Kay


_

I have this piece of code (taken from this question):

var walk = function(dir, done) {
    var results = [];

    fs.readdir(dir, function(err, list) {
        if (err)
            return done(err);

        var pending = list.length;

        if (!pending) 
            return done(null, results);

        list.forEach(function(file) {
            file = path.resolve(dir, file);
            fs.stat(file, function(err, stat) {
                if (stat && stat.isDirectory()) {
                    walk(file, function(err, res) {
                        results = results.concat(res);

                        if (!--pending)
                            done(null, results);
                    });
                } else {
                    results.push(file);

                    if (!--pending) 
                        done(null, results);
                }
            });
        });
    });
};

I'm trying to follow it, and I think I understand everything except for near the end where it says !--pending. In this context, what does that command do?

Edit: I appreciate all the further comments, but the question has been answered many times. Thanks anyway!

shareeditflag
151
 
It's a wonderful way to confuse the next person to maintain the code. – Eric J. Dec 16 '15 at 22:46
168
 
!~--[value] ^ true I call code like this "job security" – TbWill4321 Dec 16 '15 at 22:47

_

350down voteaccepted

! inverts a value, and gives you the opposite boolean:

!true == false
!false == true
!1 == false
!0 == true

--[value] subtracts one (1) from a number, and then returns that number to be worked with:

var a = 1, b = 2;
--a == 0
--b == 1

So, !--pending subtracts one from pending, and then returns the opposite of its truthy/falsy value (whether or not it's 0).

pending = 2; !--pending == false 
pending = 1; !--pending == true
pending = 0; !--pending == false

And yes, follow the ProTip. This may be a common idiom in other programming languages, but for most declarative JavaScript programming this looks quite alien.

shareeditflag
421
 
ProTip™: Never do this in your code, it's ridiculous. – Naftuli Tzvi Kay Dec 17 '15 at 0:57