Questions tagged [type-coercion]

In weakly typed languages, type coercion is where a data type is converted by the interpreter from one type to another (such as a string to an integer). This most often occurs in comparing two values. Use for questions where type coercion is an issue with your code.

Type coercion occurs in weakly typed languages (like or ). Consider this PHP code

$x = '1'; // string
$y = $x + 1;
echo $y;

$x is a string, but we call it like an integer when setting $y. So the PHP engine coerces '1' (which is a string data type) into an integer for the purposes of math. As such, the script echoes 2 because the string 1 can be coerced neatly into integer 1. But not everything is so neatly handled

$x = 'a';
$y = $x + 1;
var_dump($y);

Now, 'a' is not readily coerced into a number. As such, we get back integer(1) because PHP coerces strings to 0 (modern PHP emits a E_WARNING that this is happening).

This most often rears itself in doing comparisons. Consider this code

$x = 'Something';
echo (strpos($x, 'Some') != false) ? 'Found it!' : 'Did not find it';

This script doesn't run like we expect. It tells us it didn't find it when we know it should have found it. The problem is that strpos can return a boolean false or the position of where it found the match. In this case, the match was at position 0. Our test then becomes

if( 0 == false )

Type coercion nails us here because 0 is coerced into false in PHP. PHP and Javascript both have a workaround for this, however. We can use === and !== to tell the interpreter to not coerce before comparing. If we tell PHP not to coerce the 0, we get back the results we expect

echo (strpos($x, 'Some') !== false) ? 'Found it!' : 'Did not find it';
108 questions
1
vote
2 answers

Apps for Office 365 - Return selected text with styling and formatted

I created an Add-In App for Office365 (Word, Excel and Powerpoint) and i want to get the selected text inside my app, with new lines and styling. I am using the following code to do that function getSelectedData(hasSelectionCallback,…
Nitan Alin
  • 63
  • 1
  • 4
1
vote
1 answer

JavaScript type coercion with strings and indexing

In the below snippet why does whatDoesItDo() function return "fail" as string? It would be helpful if someone can explain the concept behind such behavior. function whatDoesItDo() { return (![] + [])[+[]] + (![] + [])[+!+[]] + ([![]] +…
Flake
  • 1,236
  • 16
  • 28
1
vote
4 answers

If statement with only a number in Javascript

I found this function to put numbers in fractions and I am trying to figure out what everything means. There is one thing I can't figure out. Here's the code: function reduce(numerator,denominator) { var gcd = function gcd (a,b) { if (b) { …
michaelpri
  • 3,301
  • 3
  • 29
  • 43
1
vote
3 answers

If I use two negation operators on a string am I using type coercion?

Consider the following code: !!('foo'); The negation operator uses the abstract operation ToBoolean to perform a type conversion, but my question is - does this involve type coercion?
Ben Aston
  • 45,997
  • 54
  • 176
  • 303
1
vote
2 answers

Checking range with command line arguments

Working on a simple C program I'm stuck with an if test: int line_number = 0; if ((line_number >= argv[2]) && (line_number <= argv[4])) gcc says: cp.c:25: warning: comparison between pointer and integer cp.c:25: warning: comparison between…
Zenet
  • 6,160
  • 13
  • 35
  • 40
1
vote
1 answer

Error regarding using a block within a block in Ruby - Array can't be coerced into Fixnum (TypeError)

This is in regards to project Euler problem #1. When I run this code line by line in irb, I get the expected answer, but when I run it from a .rb file, it throws error "Array can't be coerced into Fixnum (TypeError)" Code: # defines the list of…
josiah
  • 1,216
  • 1
  • 10
  • 27
1
vote
1 answer

WTForms How to use a DecimalField which generates proper field errors on bad input

Have a look at this example class MyForm(ForM): ...snip... quantity = DecimalField(u'Quantity', [NumberRange(1, 8)]) ...snip... This works nicely if the user is co-operative and enters something that can be coerced to a numeric type. …
idbentley
  • 4,091
  • 3
  • 29
  • 48
1
vote
2 answers

Unexpected conversion of $_GET["var"] to integer

I have the following snippet in a page running under PHP 5.4.10 (notice the === in comparison). $list_all_pages = False; $reqs_per_page = 50; $start_page = 0; if (isset($_GET["p"])) { echo("Debug: " . $_GET["p"] . "\n"); if ($_GET["p"] ===…
1
vote
0 answers

Flex Custom Event - Type Coercion Error - Application domain related?

I've been looking at answers for my problem, I think I may be on the right track but I just can't understand how to implement the solution. I need help. I have a class, RootPackage.Utils.SelectableGraphic.as, a widget,…
0
votes
2 answers

Is there a way of strictly enforce the type that can be used. (Very Explict Casting)

Is there a way of "strictly" con-straining or enforcing the type that can be use. S <: T Something like Method( value As T ) ' Any Type of T including subtypes of T Method( value Is T ) ' Only take a T not a subtype of T I can do this at…
Adam Speight
  • 630
  • 9
  • 21
0
votes
1 answer

Grails automatically coerce strings into one of my domain classes

I have a domain class like: class MyDomainClass{ String name } And an interface with a signature like: BigDecimal doBigThangs(MyDomainClass startHere) I want to be able to call it like this doBigThangs('stuff') And have it automatically coerse…
Mikey
  • 4,332
  • 9
  • 40
  • 70
0
votes
0 answers

Why console.log('10' > '5') is false in Javascript during type coercion

I am learning Javascript and was reading about type coercion. Why it's giving me false on console.log('10' > '5') console.log('10' > '5') console.log('23' > '18')
0
votes
1 answer

What happend internally in the case of null and undefined comparision?

console.log(null == undefined); // prints true console.log(null === undefined); // prints false The second statement is clear to me, no type conversion takes place and therefore false is printed. But what happens in the first statement, what is…
Dawson Smith
  • 127
  • 6
0
votes
2 answers

Why is "0" == “” false in JavaScript

In the ES5 spec, clauses 11.9.3.4-5 say: If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y). If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y. How I…
temosmoev
  • 1
  • 1
0
votes
1 answer

NAs introduced by coercionNAs introduced by coercionError in knn

When I execute this code, I get the next wrong about coercionNAs: data_test_pred <- knn(train = data_train, test = data_test, cl = data_train_labels, k = 9) NAs introduced by coercionNAs introduced by coercionError in…
Raq
  • 75
  • 5