I saw this code in reactjs open source in github
file : react.development.js
{
ReactDebugCurrentFrame.setExtraStackFrame = function (stack) {
{
currentExtraStackFrame = stack;
}
}; // Stack implementation injected by the current renderer.
ReactDebugCurrentFrame.getCurrentStack = null;
ReactDebugCurrentFrame.getStackAddendum = function () {
var stack = ''; // Add an extra top frame while an element is being validated
if (currentExtraStackFrame) {
stack += currentExtraStackFrame;
} // Delegate to the injected renderer-specific implementation
var impl = ReactDebugCurrentFrame.getCurrentStack;
if (impl) {
stack += impl() || '';
}
return stack;
};
}
Suddenly it uses {} without initailize to object what is this grammer meaning and how is this grammer called?
It's a plain block.
{
currentExtraStackFrame = stack;
}
is equivalent to
if (true) {
currentExtraStackFrame = stack;
}
Using a block without a condition or loop is quite weird, but technically allowed. Why such code exists is a good question, and it's because it's the result of transpilation - the source code that generates this is
const ReactDebugCurrentFrame = {};
let currentExtraStackFrame = (null: null | string);
export function setExtraStackFrame(stack: null | string) {
if (__DEV__) {
currentExtraStackFrame = stack;
}
}
if (__DEV__) {
ReactDebugCurrentFrame.setExtraStackFrame = function(stack: null | string) {
if (__DEV__) {
currentExtraStackFrame = stack;
}
};
// Stack implementation injected by the current renderer.
ReactDebugCurrentFrame.getCurrentStack = (null: null | (() => string));
...
When the source code is transpiled to a JavaScript bundle, if the __DEV__ setting is true, in order to faithfully transpile the existence of a block, it appears that if (__DEV__) { is simply replaced with a plain block - which they might consider nicer than having to do a runtime check for the same thing (which would require a tiny bit of additional code to send over the network and a tiny bit of extra processing for clients).