What is exclamation mark in javascript

The Double Exclamation Operator (!!) in JavaScript

In JavaScript, the double exclamation operator converts an Object to Boolean. This happens such that “falsy” objects become false and “truthy” objects become true.

This is a comprehensive guide on the double exclamation point operator.

About the Double Exclamation Operator: It’s Not an Operator

The double exclamation operator (!!) is actually the not (!) operator twice. So there is practically no double exclamation operator but rather a double not operator.

When you apply the not operator twice on a JavaScript object, here is what happens:

  • The first not operator converts the object to an inverted boolean value.
  • The second not operator inverts the inverted boolean value. In other words, this makes it the real boolean value of the object.

Example

For example, let’s apply the double explanation operation on a number:

let bool = !!23 console.log(bool)

Because a non-zero number is considered truthy in JavaScript, the above code:

But what does it mean for a value to be “truthy” or “falsy” in JavaScript?

The next chapter takes a deeper look at the concepts of truthiness and falseness.

“Truthy” and “Falsy” in JavaScript

In JavaScript, each and every object is associated with a boolean value. Another way to put it is that every JavaScript object is either true or false in a boolean context.

In JavaScript, each object is thus “truthy” or “falsy”. In other words, when converted to a boolean value:

But what types of objects are “truthy” and what objects are “falsy”?

In JavaScript, the following values are always “falsy”:

Everything else is “truthy”!

You can test the truthiness by converting the values to booleans using the Boolean() object to perform the conversion.

For example, here are some “truthy” values:

console.log(Boolean([0, 0, 0])) console.log(Boolean("Hello")) console.log(Boolean(15))

And here are some “falsy” ones:

console.log(Boolean(0)) console.log(Boolean("")) console.log(Boolean(NaN))

Why Use Double Exclamation (!!) in JavaScript?

So far you have learned that every JS value is associated with a boolean value. You also learned that the !! operator converts any object to a boolean value it would be in a boolean context.

Now you may wonder why would someone do this with a double not operator. There is a Boolean() class you can use too. The Boolean() casting would make the conversion more readable too.

Whether you use Boolean() or !! is up to a debate.

Some people consider using !! because it’s shorter than writing Boolean().

However, some people tend to favor Boolean() because it’s a more explicit way to do the typecasting.

Imagine not being familiar with the concept of !! and reading a line like this:

Читайте также:  Python check if named is defined

It wouldn’t make sense, would it?

It would be much cleaner if it was written like this:

In this expression, you can instantly tell that the writer of this piece of code wants to convert the string str to a boolean value.

To put it short, don’t use the !! operator to convert objects to Boolean. Instead, use the Boolean() object to do the conversion.

Wrap Up

Today you learned how the double exclamation mark operator works in JavaScript.

The double exclamation point converts any object to a boolean value.

To put it short, the double exclamation operator is not an actual operator. Instead, it’s a chain of two not operators. The double-not operator converts an object into the boolean value it would be in a boolean context.

  • The first not operator converts the object into an inverted boolean value based on “truthiness” or “falsiness” of the object.
  • The second not operator inverts the inverted boolean value.

This is possible because every object and value in JavaScript has an associated boolean value. In other words, every object is either “truthy” or “falsy”.

Most of the objects in JavaScript are truthy. However, values like NaN, 0, “”, and false are “falsy”.

But as it turns out, using the double-not operator is a rather obscure way to convert an object to a boolean. Instead, you should use the Boolean() object to make the conversion for easier understandability.

Источник

What’s the double exclamation mark for in JavaScript?

If you have ever noticed a double exclamation mark (!!) in someone’s JavaScript code you may be curious what it’s for and what it does. It’s really simple: it’s short way to cast a variable to be a boolean (true or false) value. Let me explain.

typeof JavaScript != ‘static’

JavaScript is not a static language, rather it is a dynamic language. That means that a variable can reference or hold a value of any type, and further, that type can be changed at any point. Whether you prefer a static or dynamic language is for you to decide.

But, we can certainly have a notion of a type in JavaScript. Here is a quick list of the various data types in JavaScript:

A boolean data type is the simplest of all data types as it is a simple bit value: 0 (false) or 1 (true).

True versus Truthy

We can set a variable to a boolean value and use it when evaluating an if-statement. Here’s our simply example.

function()  var thisIsTrue = true; if (thisIsTrue)  window.alert('It certainly is!'); > >

When the function above is executed we will get the alert It certainly is! because the variable thisIsTrue is being set to the boolean value of true .

Now, let’s look at how JavaScript can evaluate a value that is not a boolean to be casted to a boolean.

function()  var nothing = ''; if (nothing)  window.alert('Nothing'); > else  window.alert('Huh?'); > >

When the function above is executed we will get the alert Huh? because the value of the variable nothing is being evaluated to be false. This is what is commonly referred to as truthy versus falsey.

The following values are considered by JavaScript to be falseys:

The following values are considered by JavaScript to be truthys:

  • Object: <>
  • Array: []
  • Not empty string: «anything»
  • Number other than zero: 3.14
  • Date: new Date();

The JavaScript engine that is executing your code will attempt to convert (or coerce) a value to a boolean when necessary, such as when evaluated in an if-statement.

So, why double exclamation marks?

In some cases you may want to cast a variable to be explicitly boolean. Why? Well, the number one reason is that most of time developers do not use type safe comparison operators.

The type safe comparison operators are:

When using the type safe comparison operators you are both checking that the values are equal (or unequal) and that their type is the same. Without the type safe comparison operators you are allowing the JavaScript engine the freedom to coerce your variables to true or false based on the truthy/falsey logic.

To cast your JavaScript variables to boolean, simply use two exclamation signs:

function()  var name = 'Brian'; //alert 'string' window.alert(typeof name); //cast to boolean var bool = !!name; //alert 'boolean' window.alert(typeof bool); >

In the example code above we are casting the string «Brian» to a boolean value. Therefore the second alert will indicate that the variable is now a boolean value.

Brian F Love

Hi, I’m Brian. I am interested in TypeScript, Angular and Node.js. I’m married to my best friend Bonnie, I live in Portland and I ski (a lot).

Источник

JavaScript double exclamation mark explained (with examples)

What are those double not operators in JavaScript? You might have noticed a double exclamation mark ( !! ) in JavaScript code and you may be curious what that means.

First, “double exclamation mark” (a.k.a the “double bang”) isn’t an operator itself. It’s two logical not ( ! ) operators used twice.

Woman thinking

Psssst! Do you want to learn web development in 2023?

Long story short, some developers use double Not operators to explicitly convert the operand’s data type to boolean (true or false). The operand will be converted to false if its current value is falsy and true in case it’s truthy.

In JavaScript, a falsy value can be either of the following:

These none-boolean values are considered false when used in a boolean context. For instance, when you use a falsy value as an if condition, it’ll bypass the if block:

 let logged_in = null // This block isn't executed if (logged_in)  // Do something here > logged_in = '' // This block isn't executed if (logged_in)  // Do something error > 

By using !! , you can convert a non-boolean value to a boolean based on its current value.

 // Falsy values will all be false console.log(!!null) // false console.log(!!0) // false console.log(!!undefined) // false 

Needless to say, anything that’s not falsy is truthy!

 // Truthy values console.log(!!'dwd') // true console.log(!!5) // true 

JavaScript «double exclamation mark» can be used in any expression:

 let logged_in = 1 if (!!logged_in === true)  // Do something here > 

In the above code, we’re checking the boolean equivalent of logged_in and don’t care about the actual value. The value 1 is truthy, so !!logged_in will return true .

You can achieve the same results by using the Boolean constructor (without using the new keyword).

 let logged_in = 1 if (Boolean(logged_in) === true)  // Do something here . > 

But do we need this confusing technique in the first place? Let’s find out.

When do you need to use the JavaScript «double exclamation mark» syntax?

If you ask me, you’d be fine without double Not operators!

But let’s dig a little bit deeper.

JavaScript (unlike TypeScript) doesn’t have static typing. But as a weakly-typed language, it does type coercion automatically whenever needed.

What is «type coercion»? You may ask.

All primitive values in JavaScript are one of these types:

  • Undefined
  • Null
  • Number
  • String
  • Boolean
  • BigInt
  • Symbol
  • NAN (Not a number)

Type coercion is the automatic or implicit conversion of a value from one data type to another (for instance, from a string to a number) — done at JavaScript’s discretion.

 let a = '12' console.log(a * 5) // output: 60 

In the above example, the variable a contains a string ( ’12’) . When we multiply it by 5 , JavaScript casts it to a number (automatically). The result ( 60 ) confirms that.

 let a = '5' let b = 5 console.log(a + b) // output: 55 

In the above example, we have a sum expression ( ‘5’ + 5 ). This time, JavaScript chose to cast the numeric value ( 5 ) into a string. So instead of 10 ( 5 + 5 ), we got 55 — the concatenation of ‘5’ and ‘5’ .

Even if we compare ‘5’ and 5 with the equality ( == ) operator, we’ll get true , meaning they are equal — even though one is a string and one is a number.

 console.log(5 == '5') // output: true 

These quick experiments prove JavaScript converts data types in certain contexts.

To avoid unexpected behaviors, it’s advised to use the strict equality operator ( === ) over the normal equality ( == ) operator in comparisons.

The strict equality operator ( === ) returns true only if both operands are equal and of the same type. This is where you might want to use the double exclamation sign or the Boolean constructor.

 let logged_in = 1 if (!!logged_in === true)  // Do something here . > 

This might seem totally unnecessary, though. You could use the short form without explicitly casting it to a boolean data type:

 let logged_in = 1 if (logged_in)  // Do something here . > 

This will give you the exact same result.

However, if you have a good reason to compare the values with an ESLint-friendly fashion (known as the eqeqeq rule), you can convert them to their boolean equivalent before comparing them with === .

All right, I think that does it. I hope you found this quick guide helpful.

Reza Lavarian Hey 👋 I’m a software engineer, an author, and an open-source contributor. I enjoy helping people (including myself) decode the complex side of technology. I share my findings on Twitter: @rlavarian

If you read this far, you can tweet to the author to show them you care.

❤️ You might be also interested in:

Источник

Оцените статью