Skip to content Skip to sidebar Skip to footer

What Forced Function Expression To Return Value In Case There Are No Operators

I am a beginner To JS world and I have a question, according to MDN, it says that the keyword Function return a function inside an expression and the form looks like: var myFuncti

Solution 1:

There is nothing special about console.log. It is an expression because it is an argument to a function call. See the spec which shows that Arguments is ( and ) around an optional * ArgumentList* which is either AssignmentExpression or ArgumentList , AssignmentExpression (i.e. one or more expressions, separated with comments).

Solution 2:

Console.log has parameters, which will be variables inside its function body

console.log(obj1 [, obj2, ..., objN]);

When you call

console.log(function(){return"someThing"});

you assignfunction(){return "someThing"} to console.log's first parameter variable.

Solution 3:

Starting from the basic, a function in JS is an Object.

When you use the assignment operator, you are returning the Object created by defining that function.

var thisIsAnObjectFunction = function(){return"someThing"};
// to get the "someThing" string you need to call the functionthisIsAnObjectFunction();
-> "someThing"

Each Object in JS has a form of serialization, coming from the original Object prototype, which is encoded in the toString() function.

This means that when you use an operation that expects a string as input and you pass an Object, the Object will be serialized calling the toString().

console.log( [string1[, string2[, ..., stringN]]] );

The console.log function expects strings as input, otherwise it tries to cast any input to its string form.

What happens in your code is that you are effectively passing this thisIsAnObjectFunction variable to the console.log function, hence it tries to serialize it:

console.log(thisIsAnObjectFunction);

What you probably want to do instead is probably print the result of the execution of the function:

console.log( thisIsAnObjectFunction() );

Or without using the artificial variable I created:

// note the round brackets at the end of the function statement that execute the function straight after its definitionconsole.log( function(){return"someThing"}() );

Post a Comment for "What Forced Function Expression To Return Value In Case There Are No Operators"