First of all, this story is based on Stephen Curtis -33 Fundamentals Every Javascript Developer Should Know and you can read it here.
I thought it is great concepts to know although it is not a requirement. So i decided to learn and explain these concepts one by one.
#7. Expression vs Statement
There’s two kinds of syntatic categories in javascript, statements and expressions.
Expression
Expression is a piece of code that resolves to a value. In other words, just something that returns a value.
const age = 20; //20
In above example, equal sign =
expects an expression. Since 20
is an expression that resolves to the value 20
, it totally makes sense. Another expression that resolves to the value 20
could be 5+15
or 10*2
and so on.
const getAge = () => 20;const age = getAge(); // 20
A function call getAge()
is also an expression. Because when we call function getAge()
the value 20
is returned and this call will be replaced with the value 20
it returns.
The function call will be resolved to a value, therefore it’s an expression.
Statement
A statement is just an instruction. ( if, else, else if, for, while, … )
You can not put statements where expressions are expected. For example, since equal sign =
or console.log()
expects an expression, we couldn’t use statement like this way.
const age = if (true) {
return 20;
}; // errorconst name = while (true) {
return 20;
}; //errorconst address = for (let i = 0; i < 10; i++) {
return 20;
}; //errorconsole.log(const age); //error
Function expression vs Function declaration
We define a function using function expression or function declaration.
Their syntax is like below.
const add = (a, b) => a + b; // function expressionfunction add() {
return a + b;
} // function declaration
The one of outstanding difference they have is something called hoisting.
console.log(add(1, 2));function add(a, b) {
return a + b;
}
For example, in this case, 3
is logged on the console even if we didn’t declare add
function before using it. It is because of hoisting. Hoisting means before executing code, javascript takes all of your declarations and put them at the top. As a result, javascript is executing code below
function add(a, b) {
return a + b;
}console.log(add(1, 2));
However, when we declare function with function expression, it is not hoisted and result in error.
console.log(add(1, 2));const add = (a, b) => a + b;
Conclusion
Most of the code can be splited to piece of small expressions and statements. This will be helpful when you solve your next bug that is originated from these simple concept.
reference: video