When you start learning JavaScript or similar programming languages it seems somewhat understandable in the beginning. You do something if the condition results in true, else you do something else. It is normal English written as very specific and detailed instruction to the machine. As you progress in your learning you see things that does not make sense right away. Why are there question marks (?) and exclamation marks (!) in the code?
​
Is the question to the machine or the programmer?
Are we shouting out code now!! Can you hear me?
​
Of course not, that would be ridiculous. Both question mark (?) and exclamation mark (!) has a special meaning when we are writing code.
When using the exclamation mark (!) in code it is the same as saying not in English.
​
Okay, that is good to know, right? But why?
A exclamation mark (!) negates an expression. This comes from boolean algebra where we have AND, OR and NOT operators. So this helps us when dealing with boolean algebra in our code. It's also a great way to write shorter and more compact code.
One place where the exclamation mark (!) really shines is when you want the opposite value of the current state. Using the exclamation mark (!) in this situations reduce the amount of code by a lot.
Let us look at an example where we want to set the value for a toggle button to the opposite of current state. The state is a boolean, true or false.
In the first example we use code without exclamation mark (!).
It's not a lot of code, but it can be done shorter. Look here:
Wow! That was short!
So instead of spelling out what to do if the value is true and then what to do if the value is false, we just tell the code to update state with the opposite of current state.
This was a more specific example, and as you might have noticed, not all or not most code is like this. So there must be other places where exclamation mark (!) can be used more frequently?
Other ways to use the exclamation mark (!) is as a short hand for === false.
So instead of doing this:
We can do just this:
Understanding and being able to read/write code is important, that is why you should learn and understand all of it. Maybe using the exclamation mark (!) is not your thing, but others might use it and you should be able to read their code also.