declaring and calling a function in one line strangeness

Can anyone explain, why this returns 'string'?
function testTwo() { return 'return'; }('string')
function testTwo() { return 'return'; }('string')
6 Replies
Rägnar O'ock
Rägnar O'ock16mo ago
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
(function great(name) { return 'hello '+ name + '!'})('billy')
(function great(name) { return 'hello '+ name + '!'})('billy')
Wolle
Wolle16mo ago
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 😄
Rägnar O'ock
Rägnar O'ock16mo ago
exactly
Wolle
Wolle16mo ago
I am still used to only think of ; as line end 😄
Rägnar O'ock
Rägnar O'ock16mo ago
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)
13eck
13eck16mo ago
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:
function testTwo() { return 'return'; }('string')
function testTwo() { return 'return'; }('string')
And sees a function declaration and a grouping operator, so it adds the semicolon to separate the two:
function testTwo() { return 'return'; };('string')

// effectively
function testTwo() { return 'return'; };
('string');
function testTwo() { return 'return'; };('string')

// effectively
function testTwo() { return 'return'; };
('string');
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.