Operator on the right side of assignment

I’m following a video tutorial on D3 and there is an assignment syntax I’ve never saw. Also I couldn’t find anything on the web. Isn’t it weird?

import { select } from 'd3';
const svg = d3.select('svg');
const width = +svg.attr('width');

The plus sign at the right of the assignment confuses me.
I don’t understand how it works.
If I remove it and log width in the console I get null, which I guess is to be expected as svg at this point doesn’t have a width attribute.
If I leave it there, width is equal to zero.
Any insights on the matter?
Also I’d appreciate any relevant link to this feature.
Thanks!

It is doing type coercion/conversion.

typeof +'1'
'number'

typeof '1'
'string'

I’m personally not a huge fan of doing it like that but I know a lot of people use it. I think it depends on the context. Sometimes it can be a little confusing.

1 Like

Ah! Didn’t think about that…it certainly was confusing to me.
Thank you

1 Like

If you have never seen it before it is definitely confusing. But even when you know about it I find in some contexts it can still make the code harder to read (or at least quickly scan). Explicit conversions are usually easier to spot in code than implicit.

2 + +'2'
4
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.