Is this a valid example of a piece of code changing from a statement to an expression because the syntax of the code has changed?

Viewed 73
function f() {return 5;}; 
var x = f();

The execution of a function statement by itself (f()) is an expression statement. However, in the code snippet above (var x = f();), is the f() part of the code no longer an expression statement - and therefore just an expression - because statements can’t appear where expressions are expected?

1 Answers

An expression is any statement (or part of the statement) that return some result. Whenever we call a function it is an expression because it returns a value. Even if the function body does not include any return statement, it returns undefined by default.

The statement var x = f(); is not an expression because it returns no value. However, the left side f() is still an expression because it will return some value. x = f() is also an expression because it also returns some result. We can also verify that x = f() is an expression by putting this in if condition. However, that part var is not an expression, and putting it in if condition will throw an error.

I hope this clears your confusion. To answer this question I took little help from here

Related