Beginners question on numeric conversion

Joined
Feb 15, 2021
Messages
96
Reaction score
0
Code:
let str = "123"; alert(typeof str); //
string let num = Number(str); //
becomes a number 123 alert(typeof num); // number


kindly explain

Code:
let num = Number(str); // becomes a number 123

i dont follow

thanks!!
 
Joined
Jul 3, 2022
Messages
93
Reaction score
23
Double or single quotes make the expression between them a string, Number() turns /* in case it consists of digits, but is a string */ the expression between it's braces into a number. Nothing but a simple magic <wink>
 
Joined
Feb 15, 2021
Messages
96
Reaction score
0
thanks!

another question, please

The unary plus or, in other words, the plus operator + applied to a single value, doesn’t do anything to numbers. But if the operand is not a number, the unary plus converts it into a number.

For example:

Code:
// No effect on numbers
let x = 1;
alert( +x ); // 1

let y = -2;
alert( +y ); // -2

// Converts non-numbers
alert( +true ); // 1
alert( +"" );   // 0

please help with the whole concept
 
Joined
Mar 11, 2022
Messages
227
Reaction score
32
+ isn't convert anything to a number at all.

Code:
var a = "1";
var b=2;
var c= a + b;
alert(c);

//WILL ALERT 12 (1+2)
//BUT

var c=parseFloat(a)+b;
alert(c);
//WILL ALERT 3;
 
Joined
Jul 3, 2022
Messages
93
Reaction score
23
+ isn't convert anything to a number at all.

Code:
var a = "1";
var b=2;
var c= a + b;
alert(c);

//WILL ALERT 12 (1+2)
//BUT

var c=parseFloat(a)+b;
alert(c);
//WILL ALERT 3;

if you put + to the proper place some strings will suddenly turn to numbers:

JavaScript:
const a = "1";
const b = 2;
const c = + a + b;
alert(c);
 
Joined
Mar 11, 2022
Messages
227
Reaction score
32
Yes my bad. I've tried it by myself. Anyway. That's a really bad habit of coding which nobody should ever get used to. NEVER MIX TYPES.

But my claim is still right. An Math operator isn't convert any type to another type. In that particular example it worked.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,479
Members
44,900
Latest member
Nell636132

Latest Threads

Top