On the fly function expression doesn't throw error when triggering with first class

31 Views Asked by At

I am learning Javascript and I came across these concepts of function expressions & first class functions.

While I do understand their definition, I am unable to understand why my code behaves the way it does.

I have a first class function which takes in 2 arguments - function name & text. While trying to learn I ended up calling it with 2 different types of functions - one with the expected parameters and another with unexpected parameters

My doubt is, why isn't there any error getting thrown my way when there are unexpected parameters count

Code snippets

// function as a first-class function
function firstClassFunction(functionName, text) {
    functionName("Hello from first-class function"+ " + " + text);
}

// function expression with on the fly function i.e. giving function on fly to first-class functions
firstClassFunction(function(text) {
    console.log(text + " + " + "Hello from function expression on fly")
}, "Additional text")


// function expression with on the fly function i.e. giving function on fly to first-class functions
firstClassFunction(function() { // Not sure of this behaviour
    console.log("Hello from function expression on fly")
}, "Additional text")

Output

Hello from first-class function + Additional text + Hello from function expression on fly
Hello from function expression on fly

I am unable to understand why line 2 of the output is there at all and why there is no error coming up

Thanks in Advance!

1

There are 1 best solutions below

0
On

That's just how javascript works, it's not a strictly typed language. You are allowed to pass in more arguments / less arguments to a function that it expects. You can even get the arguments that you didn't know would be there:

function demo() {
    console.log(Array.from(arguments))
}


demo('a', 'b')

If you want a little more type safety, I'd recommend looking into typescript.