Juan Carlos Oropeza Juan Carlos Oropeza - 5 months ago 8
jQuery Question

are javascript variable string by default?

Im creating a ZoomIn icon for my cars.

<img src="~/Content/center-icon.png" id="center-@car.Car_ID" data-x=@car.X data-y=@car.Y />
^^ ^^ float


I get the data from the clicked event

var $carCenterId = $('#' + event.target.id)

var x = $carCenterId.data("x");
var y = $carCenterId.data("y");

carZoomCenter(x, y);


But my function wasnt working because treat x and y as strings.

function carZoomCenter(x, y) {

console.log(typeof x); // return string

x = Number(x);
y = Number(y);

console.log(typeof x); // return number

var iconFeature = new ol.Feature({
geometry: new
ol.geom.Point(ol.proj.transform([x, y], 'EPSG:4326', 'EPSG:3857')),
name: 'Null Island ', ^^^^ fail if are string
population: 4000,
rainfall: 500
});
}


After adding
Number()
, function is working ok. I know javascript doesnt declare types. but Im wondering if that is the way to do it or if I missing something.

Answer

In this case the value will be a string because under the hood, the data() jQuery method is calling the JavaScript getAttribute() method on the DOM element. And attribute values on HTML elements are string values and are returned as strings.

You can also look into the parseFloat() and parseInt() methods of JavaScript to force the conversion to a number.

var x = parseFloat($carCenterId.data("x"));
var y = parseFloat($carCenterId.data("y"));

JavaScript does not default things to string. It does support types, but it also doesn't enforce them unless you want it to. JavaScript will try to coerce types by inferring what you want. Like this: var x = "2"; var y = x + 2; console.log(y == 4); //logs true

JavaScript will coerce the string into a number and y will be the result. Similarly: var i = 2; var k = i + "";

k will be a string value.

Types can seem to be very fluid, and JavaScript can coerce them in unexpected ways if you aren't careful. When you have logic that requires variables to be specific types, it's best to force them into the types you need.