-6

I don't understand this because java is my first programming language.

In java, variables inside of parentheses should be declared

For example

public int checkUserName(int minLength){
    //some codes 
}

but in javascript

function checkUsername(var minLength){
//some codes
}

shows an unexpected token var error

I know Java and JavaScript are two different languages but I just want to know why isn't it allowed in JavaScript. I know it is not allowed I just want to know why.

I asked this because my JavaScript book does not explain me why JavaScript does not allow that. It just says you should write so but not WHY.

halfer
  • 19,824
  • 17
  • 99
  • 186
ProgramLover
  • 91
  • 2
  • 9

2 Answers2

2

When I started to learn second language I had many similar questions, but when you learn third and so on you are just deal with it :) in every two languages you will find something similar and something different

you have not to declare minLength here

function checkUsername(var minLength) {
    //some codes 
}

try

function checkUsername(minLength) {
    //some codes 
}

You might be interested in TypeScript, it is javascript after all, but looks pretty similar to java. for example:

public checkUserName(minLength: int ): int {
    //some codes 
}
qiAlex
  • 4,290
  • 2
  • 19
  • 35
1

In a comment you've clarified:

I know [it isn't allowed] but I just wondered why isn't it allowed

Because until ES2015 it would have been completely redundant and pointless; just having minLength there is sufficient declaration, since JavaScript's variables and parameters are not typed. Moreover, var would have been misleading, as minLength isn't a variable, it's a parameter. (Functionally, they're very nearly the same thing as far as the function's code is concerned other than the obvious difference that the initial value of a parameter comes from outside the function; but they aren't the same thing.)

In ES2015 and above, there's an argument for allowing an optional const to indicate that the parameter's value can never be changed by the function, but I haven't seen any proposal for that advanced (so far).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875