简体   繁体   中英

! Logical Operator and Scope in JavaScript

I'm working through JavaScript Essential Training on Lynda.com and I am having a hard time wrapping my head around the logic of a concept.

I have this code below which sets a timer to run every thousandth of a second by setting an interval using setInterval.

var timerRunning = false;

function start() {
    let textEnteredLength = testArea.value.length;
    if (textEnteredLength === 0 && !timerRunning) { //textEnteredLength is 0 and timerRunning is false
        timerRunning = true;
        interval = setInterval(runTimer, 10); //runTimer every 10 milliseconds (thousandth of a second)
    }
}

Basically, I am confused because in the tutorial, timerRunning is a global variable set to false at the top of the code (var timerRunning = false;)

Therefore, doesn't !timerRunning mean that timerRunning is true? Or, is it because logically !timerRunning means not timerRunning AKA false regardless of what the global variable is set to initially?

EDIT:

Nevermind... I somehow misunderstood the logic of the code, apparently I need to sleep more. For some reason I was thinking var timerRunning = false set the value of timerRunning in the if statement, and therefore, !timerRunning would be true, when really timerRunning really just means false, and we continue to the inside of the if statement because the if statement is true.

Thanks for your help.

At first run of start , timerRunning is false , meaning !timerRunning is true . The consequence is the if -block is run only once, the first time start is called.

!timerRunning is like false == timerRunning because of the exclamation mark. This is in every programing language AFAIK. Read more about it here: What does an exclamation mark before a function really mean

 var timerRunning = false; console.log('false ... ' + timerRunning); console.log('true cause it is false ... ' + !timerRunning); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM