What is Type Coercion in Javascript?

What is a type of coercion in javascript?

For example, when using == instead of === ?

+82
javascript
Nov 11 '13 at 20:52
source share
8 answers

The type of coercion means that when the operands of the operator are different types, one of them will be converted to the "equivalent" value of the other type of operand. For example, if you do:

 boolean == integer 

the logical operand will be converted to an integer: false becomes 0 , true becomes 1. Then two values ​​are compared.

However, if you use the conversion operator without the conversion === , such a conversion does not occur. When the operands are of different types, this operator returns false and only compares values ​​when they are of the same type.

+118
Nov 11 '13 at
source share

Let's start with a short entry to type systems that I think will help you understand the general idea of ​​tick compulsion.

The language type system defines rules that tell us which data types exist in that language and how they can be combined using different operators. For example, one of these rules may indicate that the plus (+) operator acts only on numbers. These rules exist primarily so that you do not shoot in the leg. But what happens when a programmer breaks this rule in a program? Theres nothing stopping the programmer from typing {} + {} or "hello" + 5 in the program, even if the language does not think that these expressions make any sense.

What ultimately happens in these situations depends on how strict the language is with its type rules.

The language type system often contains one of two positions that you violate its rules:

  • Say "hey it's not cool!" and immediately crash your program.
  • Say: "I can’t do anything with {} ... but I can do something with numbers" and try to convert {} to a number.

Languages ​​with type systems, which occupy the first position about their rules, are colloquially called "strongly typed" languages. They are strict, not allowing you to break his rules. Those that take the second approach (such as JavaScript) are called "weakly typed" or "weakly typed" languages. Of course, you can break the rules, but do not be surprised when it converts the type of data that you described in your program, in order to comply with its rules. This behavior is known as ... (drum roll) ... a type of coercion .

Now let's look at some examples in JavaScript. First, let's start with an expression that does not lead to a type of coercion.

 5 + 5 

Using the + operator with two numbers, which are perfectly valid. The program will relate + to the value "add" and happily add two numbers. No conversion required.

But what about ...

 [] + 5 

Oh oh In JavaScript + can mean adding two numbers or combining two lines. In this case, we do not have two numbers or two lines. We have only one number and an object. According to rules such as JavaScript, this makes no logical sense. Since his forgiveness that you are breaking his rules, instead of crumbling, he is still trying to figure it out. So what does javascript do? Well, he knows how to concatenate strings, so he converts both [] and 5 to strings, and the result is the string value "5".

What is the deal with == and === comparison operators? Why are there two comparison operators?

== not protected from JavaScripts type conversion behavior. Expressions such as 5 == "5" will be evaluated as true because JavaScript will try to convert one of them so that it compares the same data type.

In many cases, this is undesirable because you probably want to know if any material you are comparing is of a different type so that you can decide what to do with it. This is where the === operator comes in. When you use === , type conversion will not be. Therefore, the expression 5 === "5" will be evaluated as false.

+39
Jul 08 '16 at 3:03
source share

In Python, if you try to add, say, strings and integers, you get an error:

 >>> "hi" + 10 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot concatenate 'str' and 'int' objects 

But in JavaScript you do not. 10 converted to a string:

 > "hi" + 10 "hi10" 

"Type of coercion" is simply a bizarre misnomer for the foregoing. In fact, no language has “types” in the sense of Java or C or other languages ​​with systems of a static type. How languages ​​view interactions between different non-statistical meanings is a matter of choice and agreement.

+6
Nov 11 '13 at 20:57
source share

let me explain the type of coercion with the following example

Type Coercion means that Javascript automatically ("on the fly") converts a variable from one data type to another

Example: 123 + "4" usually causes an error, but in Javascript, due to type coercion, it leads to 1234 line

 if(23 == "23"){ console.log(" this line is inside the loop and is executed "); } 

In the above code, due to the type of coercion - JavaScript considers 23 (number) and "23" (string) to be one and the same. this makes the condition true and prints console.log

Otherwise

 if(23 === "23"){ console.log(" this line is inside the loop and is NOT executed"); } 

In === case, Javascript does not execute Type Coercion, and since 23 is a number and "23" is a String, and because of === these two data types are different and lead to a false state. It does not print console.log

In simple words

In this case, = is an assignment operator that assigns values, such as var a = 3; , etc

(below for comparison)

In this case == Javascript converts / forces the data type to another, and then compares it.

In this case === Javascript does not convert or enforce a data type

To avoid errors and for debugging purposes === is mainly used

Please let me know the accuracy of the above information.

+3
Apr 05 '18 at 19:48
source share

a == b means that javascript will evaluate a against b based on whether the values ​​can be evaluated equally. For example, false == 0 will evaluate to true, since 0 is also a Boolean false. However, false === 0 will evaluate to false because a strict comparison, 0 is not the same physical value as false. Another example is false == '' So basically free comparison versus strict comparison, because javascript is a freely typed language. In other words, javascript will try to convert the variable based on the context of the code, and this will cause things to become equal if they are not strictly compared. php also has this behavior.

+1
Nov 11 '13 at
source share
 var str = 'dude'; console.log(typeof str); // "string" console.log(!str); // false console.log(typeof !str); // "boolean" 

An example of a variable that is initially declared as a string, forcibly entered into a boolean value with! Operator

0
Nov 04 '17 at 17:56 on
source share

If the data type is not equal to each other, then coercion occurs. for example 3 == "3" or boolen == integer

0
Mar 30 '18 at 12:07
source share

What is coercion:

A type of coercion in javascript occurs when the Javascript engine has to perform a certain operation for which it needs data of a certain type. When the engine encounters data of a specific type that is not applicable to the operation, it then forces the data to a specific type. This is necessary because variables in javascript are dynamically typed, which means that a value of any type can be assigned to this variable.

Example:




 if(1){ // 1 gets coerced to true } if(4 > '3') { // 3 gets coerced into a number } 44 == "44" // true, the string 44 gets converted to a nr 

Boolean coercion:

When forcing javascript, all values ​​are converted to true with the exception of the following values, which are forcibly applied to false :

 console.log(!!""); // false console.log(!!0); // false console.log(!!null); // false console.log(!!undefined); // false console.log(!!NaN); // false console.log(!!false); // false 

Also note that in the above example double! operator is used. ! The mark operator enters a value in a boolean value with the opposite value. We can use this operator twice to convert any value to a boolean.

0
Sep 07 '18 at 8:04
source share



All Articles