user31782
user31782

Reputation: 7589

Why don't we use the data type for function parameters in javascript?

In javascript if I have to use a variable foo then I have to first define it as var foo. But when we use parameters in functions, e.g. as:

function myfunc(bar) {  
  alert(bar);  
}

why don't we write function myfunc(var bar) {...} instead? How does javascript know that bar is a variable? I remember that in C++ we have to tell that the compiler that the parameter being passed to the function is a variable as

int myfunc ( char bar[] ) {...}

Upvotes: 1

Views: 515

Answers (4)

Stian Standahl
Stian Standahl

Reputation: 2619

As James111 said. Javascript does not support adding types to input parameters.

If you really want this functionality, you can use a language that compiles down to Javascript. For example Typescript or Dart.

If you want to program in pure Javascript you can use visual studio code, since it has some nice commenting features for tagging input parameters

Upvotes: 0

Bergi
Bergi

Reputation: 664405

How does javascript know that bar is a variable?

Because all parameters of functions are local variables in JavaScript.

And in contrast to C++, variables don't have a type, so you don't have to (and cannot) specify types for function parameters either.

Upvotes: 0

deceze
deceze

Reputation: 522042

The syntax foo = bar is ambiguous, it could be the initialisation of a new variable, or it could be assigning a value to an existing variable. Since that's important with regards to scope in Javascript, you need to explicitly use var foo for initialising a new variable.

function (foo) on the other hand is entirely unambiguous. foo is a function parameter and therefore also functions as a variable initialiser. There's no point in distinguishing between function (var foo) and function (foo), both of them would do the same thing.

myfunc ( char bar[] ) in C does something completely different; char here is a type hint. Javascript doesn't have type hints. It only has the var keyword (and related let and const) for initialising new variables, but that doesn't have anything to do with types or type hints.

Upvotes: 4

James111
James111

Reputation: 15903

Because JS doesn't support it. Simple as that!

Upvotes: 2

Related Questions