0

My understanding is that bellow code will create an array name digits which contains all digits from n, I'm I right?

var n = 123456789; var digits = (""+n).split("");

But I did'n understood (""+n) ? Can anyone help me? Thanks in advance.

5 Answers 5

1

n is type of a number, with (""+n), you are basically converting n to a string, so you can use split method. numbers do not have a split method

Sign up to request clarification or add additional context in comments.

Comments

1

It is doing the job of implicit type casting from int to string. For ex.

4 + 2

returns 6

4 + 2 + "2"

returns 62

"2" + 2 + 4

returns 224

The integers following "" are implicitly converted to string and cancatenated.

Comments

1

var n = 123456789; create a variable n of numeric type. When you use +"" with a variable of numeric type javascript autamatically treat it as string and the operation return a string. So (""+n) will cast the n variable to string type.

Comments

1

When concat a number with string, js cast it to string. In your code, n is number, but when concat with a empty string(""), casting to string. In other way you can call toString() function. You can run follow snippet to try it

var n = 123456789; 

console.log(typeof n); //number
console.log(typeof (""+n)); //string
console.log((""+n).split(""));
console.log(n.toString().split(""));

1 Comment

Thank you Mohammad for the detail explanation.
1

(""+n) means type casting the variable n into string

var n = 32;  // n is integer type
n = "" + n; // now n is string type (n = "32")
var digits = n.split("");//execute string split function
//now digits = ['3','2'] (array of chars or single string charector)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.