Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Effect of x = +x in JavaScript [duplicate]

Tags:

javascript

Going though the asm.js documentation I've observed this strange (to me at least, quite new to JS) snippet all over the sample code:

function test(x) {
    x = +x; // THIS
    ...
    return +(x*y);
}

What is the purpose of the + on the first line?

like image 786
adrianp Avatar asked Apr 08 '13 06:04

adrianp


People also ask

What is the result of 2 === 2 in JavaScript?

Type converting equality (==) means automatically it will covert the variable to value irrespective of data type; either it is a string or a number. This means "2" will be equal to 2 ("2" == 2 it will return true).

What does X mean in JavaScript?

var is the keyword that tells JavaScript you're declaring a variable. x is the name of that variable. = is the operator that tells JavaScript a value is coming up next. 100 is the value for the variable to store.

How do you write x 2 in JavaScript?

pow(x, 2) .


2 Answers

Its simply used for casting a value with another type to number. Additonally it will return NaN if the value after that + symbol could not get converted into a number.

FIDDLE

From the book Javascript and Jquery - The Missing Maunal

var numOfShoes = '2';
var numOfSocks = 4;
var totalItems = +numOfShoes + numOfSocks;

Adding a + sign before a variable (make sure there’s no space between the two) tells the JavaScript interpreter to try to convert the string to a number value—if the string only contains numbers like “2”, you’ll end up with the string converted to a number. In this example, you end up with 6 (2 + 4). Another technique is to use the Number() command like this:

var numOfShoes = '2';
var numOfSocks = 4;
var totalItems = Number(numOfShoes) + numOfSocks;

Number() converts a string to a number if possible. (If the string is just letters and not numbers, you get the NaN value to indicate that you can’t turn letters into a number.)

like image 156
Rajaprabhu Aravindasamy Avatar answered Nov 05 '22 18:11

Rajaprabhu Aravindasamy


Perhaps I am reading this wrong but from the specs http://asmjs.org/spec/latest/#parameter-type-annotations

is that casting it as a double?

like image 39
thealfreds Avatar answered Nov 05 '22 18:11

thealfreds