0

Why can't I multiple strings in JavaScript ?

In python I can do this print("ha" * 10) While in JavaScript it won't work and result undefined unless I do this alert("11" * 2) //outputs 22 not 1111 I know I can just use "for" loop but I want to know why JavaScript treats a "string" as an "integer".

11th Mar 2020, 6:12 PM
Hamdy Elzonqali
Hamdy Elzonqali - avatar
6 odpowiedzi
+ 12
You can use the JavaScript repeat() method of a string: 'Hi'.repeat(3) // 'HiHiHi'
11th Mar 2020, 8:01 PM
Danijel Ivanović
Danijel Ivanović - avatar
+ 10
Hamdy Elzonqali you are welcome! 😊 That's just one way to do it, I'm trying to find a better answer to your question...🤔 The fundamental issue here is that JavaScript is a loosely typed language and it performs automatic type conversion on values to accommodate the operation being performed. In your example JavaScript converts the type of "11" to numeric and then applies a * multiplication operation. I don't know if I'm right but I wish someone would correct me if I didn't. Thanks a lot for deleting duplicate questions.👍 Also, take a look at this one - https://www.samanthaming.com/tidbits/22-2-ways-to-repeat-strings/
11th Mar 2020, 9:34 PM
Danijel Ivanović
Danijel Ivanović - avatar
+ 10
Hamdy Elzonqali try to read about type conversion in JavaScript. For example, • When using the plus sign operator (which JavaScript uses for both addition and concatenation) with string and number operands, JavaScript converts the number to a string and concatenates the two: console.log( 2 + '2' ); // 22 • When using an arithmetic operator on string and number operands, JavaScript will convert the string to a number: console.log( 2 * '2' ); // 4 • When JavaScript can't convert the string to a number, the result will be NaN: console.log( 2 * 'x' ); // NaN [ Edited: ] • https://www.sololearn.com/post/250999/?ref=app
11th Mar 2020, 10:27 PM
Danijel Ivanović
Danijel Ivanović - avatar
+ 4
Every language has its own set of things it can and can't do. Every choice has their own advantages and disadvantages. In Python, you have to explicitly convert a string to a number first, in JS you can in many cases just calculate directly.
11th Mar 2020, 6:19 PM
HonFu
HonFu - avatar
+ 3
Avinesh sorry I didn't realize that It was posted 3 times. I guess the bad connection was the problem. Danijel Ivanović Thank you :)
11th Mar 2020, 8:12 PM
Hamdy Elzonqali
Hamdy Elzonqali - avatar
+ 2
Why has it been asked multiple times? Wait until somebody answers your questions because otherwise it will lead to unnecessary duplicates. https://www.sololearn.com/discuss/2197010/?ref=app https://www.sololearn.com/discuss/2197013/?ref=app
11th Mar 2020, 6:36 PM
Avinesh
Avinesh - avatar