Search code examples
javascriptfunctionparameterscallbackarguments

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();
}

Solution

  • To target your specific code blocks, kindly take a look at the below code

    function sumA()
    {
      return 2;
    }
    
    function sumB()
    {
      return 3;
    }
    
    function invokeAdd(a,b){
      return a()+b();
    }
    
    console.log(invokeAdd(sumA, sumB)); //5
    

    The above code will resulted in 5. Let's break them into steps.

    When we first invoke the function invokeAdd, we passed in 2 variable sumA to be first parameter which is a and sumB as second parameter which is b. Now invokeAdd becomes something as below:

    return sumA() + sumB() 
    

    and hence return 5.

    Now let's take another example where we switch the paramter to numbers.

    console.log(invokeAdd(1, 2));
    

    We now invoke the function invokeAdd and passing in 2 parameters, 1 and 2 respectively and our invokeAdd has turned into below

    return 1() + 2();
    

    Because 1 is not a function and we have a parenthesis () beside it, JS engine will throw an error. () means execute the function

    TypeError: a is not a function

    If you wish to learn more about types in javascript, You-don't-know-JS is a very good book with detailed explainations