1

I have an array with 5 items. I want the user to choose one item.

devops_tutorials = ["Git","Jenkins","Docker","Ansible","Vagrant"];

I want the user to choose one of the options from values 1 through 5

var user_option = prompt("Which Course? 1.Git | 2.Jenkins | 3.Docker | 4.Ansible | 5.Vagrant");

Now, the typeof user_option is showing as a string. So, On the console when I'm printing the value chosen by the user, should I convert the variable user_option to number? But without typecasting, I dont understand why the below statement is working fine.

console.log("you have chosen" + devops_tutorials[user_option-1]);

And this is also working fine

console.log("You have chosen" +devops_tutorials[Number(user_option)-1]);

I expect javascript to throw an error when I'm passing the variable without typecasting. What's happening internally?

Prashanth
  • 21
  • 2

2 Answers2

2

The - operator can only be used on numbers, so when the interpreter encounters something that isn't a number on the right or left side of a -, it will try to convert it to a number. For example:

const obj = {
  valueOf() {
    return 5;
  }
};

console.log(obj - 3);

In your case, since prompt returns a string, if the string is numerical, it'll be easily converted to a value of number type automatically. No explicit type casting is necessary.

Using the - operator on something that can't be sensibly converted to a number will almost never actually throw an error - at worst, it'll usually just result in NaN:

const obj = {};

console.log(obj - 3);

Typescript, on the other hand, generally does require explicit type casting.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
2

What is probably THE main problem of Javascript is that it does all kinds of casting automatically.

While this sometimes does save some keyboard wearing, often it becomes a nightmare when debugging.

In your case you should understand that "3" - 1 in Javascript gives 2, and that "3" + 1 instead gives "31".

Welcome to hell

6502
  • 112,025
  • 15
  • 165
  • 265