declaring and calling a function in one line strangeness
Can anyone explain, why this returns 'string'?
6 Replies
because you don't actually call the function here, you define the function and define a string . the console simply prints your string
to call the function you need to put parenthesis arround the function declaration and then the parameters
So basically it takes it as two lines of code and
('string')
gets just put out, because the console doesn't know what I want from it 😄exactly
I am still used to only think of ; as line end 😄
in most cases JS doesn't care about
;
it is only important when you have multiple sets of parenthesis because it might be interpreted as an IIFE (what you are trying to do just there)It's not that JS doesn't care about
;
. It's the opposite in fact: when you don't use them the JS engine does it for you!
So the JS engine running your code sees:
And sees a function declaration and a grouping operator, so it adds the semicolon to separate the two:
So now you have a function called testTwo
and a grouping expression to be evaluated. So the function is registered and the expression string
is evaluated and returned.