• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 58
  • Last Modified:

Why add + "" to end of Math.random?

I have no idea why the empty quotes were added to the end ?
                var axel = Math.random() + "",
                

Open in new window

Does anyone know why someone would do this?

Thanks
0
894359
Asked:
894359
  • 3
  • 2
  • 2
  • +1
3 Solutions
 
Pawan KumarDatabase ExpertCommented:
I dont think it is required. Remove and run the program again and see if you get any difference or issues?

It returns a A floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive).

Lot of examples are given @ - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
0
 
894359Author Commented:
I agree it is not require and removing it has no impact but I was wondering if there was some unknown reason for it?
0
 
Pawan KumarDatabase ExpertCommented:
I must be a developer's mistake - i think unintentionally. :)
0
The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

 
Dave BaldwinFixer of ProblemsCommented:
It may be there to make sure the variable 'axel' is a string.  Since JavaScript sometimes does automatic conversions, some times you need to do something to make sure you get the type you want.
1
 
hieloCommented:
Adding + "" at the end of the above statement essentially "casts" the random number to a string (as opposed to a number).  So, after the line you posted, if you were to write:
alert( typeof(axel) );

Open in new window

it should display string.  On the other hand, if you get rid of the + "", then the type would be reported as number.  Perhaps there was a reason why the original developer needed/wanted the random number as a string.
1
 
Pawan KumarDatabase ExpertCommented:
Yes below methods can be used to convert a number to a string in JavaScript -
Pawan = Pawan+''      <<Implicit Conversion>>
Pawan = Pawan.toString()  <<Explicit Conversion>>

Although I don't like the first one since once the new developer comes it becomes difficult for him to understand the code.

Explicit conversion should always be used.
0
 
894359Author Commented:
Thank you all!
0
 
Dave BaldwinFixer of ProblemsCommented:
You're welcome!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

  • 3
  • 2
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now