Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No need to declare types in parameters in javascript?

I noticed while learning javascript that it does not require you to declare types in the parameter of a function like java does. How does the compiler know what type is passed? is there any type checking? Lets say my function handles numbers instead of strings and I pass a string?

Also normally in javascript do you not need to specify in the parameters that you are passing a function? Again how does the compiler know?

function invokeAdd(a,b){
    return a()+b();
}
like image 696
akotch Avatar asked Mar 09 '26 02:03

akotch


1 Answers

JavaScript is not a compiled language; It's an interpreted language. So no static type-checking.

To answer one of your specific questions:

Lets say my function handles numbers instead of strings and I pass a string?

You can try this out quite easily:

let number = 1;
let string = "STRING";

let addition = number + string;

console.log(addition);

Notice that all this does is concatenate the two variables. So 1 + "STRING" is 1STRING (and the result is a string type).

It's also worth noting, that variables do not have types but values do. In the above code, addition could be set to anything. You could set it as a string on one line and then a number on another and no error will be thrown (until you try to do something invalid with a number or a string). If you want to check the value of a variable before performing some action on it, you can do something like typeof addition === "string" (for example, to see if the value of the addition variable is a string).

like image 115
Kurt Avatar answered Mar 10 '26 16:03

Kurt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!