I'm trying to wrap my head around JSX. I've found a very weird behavior. This is my code:
const name = undefined;
const myFunc = () => undefined;
let template = (
<div>
{myFunc()}
{name}
{undefined}
</div>
);
ReactDOM.render(template, document.querySelector("#root"));
The output is one time: undefined
Why is the const "name" the only undefined value that is resolved to a string? What is the difference between this const and the other two expressions? (Same with Boolean and null.) Please see my code here: codepen
To check if a variable is null or undefined in React, use the || (or) operator to check if either of the two conditions is met.
To check for undefined in React, use a comparison to check if the value is equal or is not equal to undefined , e.g. if (myValue === undefined) {} or if (myValue !== undefined) {} . If the condition is met, the if block will run.
Summary. undefined is a primitive type of a variable which evaluates falsy, has a typeof() of undefined, and represents a variable that is declared but missing an initial value. null == undefined evaluates as true because they are loosely equal. null === undefined evaluates as false because they are not, in fact, equal ...
A variable is undefined when it's not assigned any value after being declared. Null refers to a value that is either empty or doesn't exist. null means no value. To make a variable null we must assign null value to it as by default in typescript unassigned values are termed undefined.
That's because JSX
is syntactic sugar for React.createElement(component, props, ...children)
It will ignore these types (see DOCS):
I just realized that this happens only on some editors like codepen because they run the code in the global context and window.name will always be a string.
window.name will convert all values to their string representations by using the toString method.
If you change the variable to something else, lets say name1
it behaves as expected.
const name1 = undefined;
const myFunc = function(){return undefined};
let template = (
<div>
{name1}
{undefined}
{myFunc()}
</div>
);
By the way, stack-snippets behave the same:
console.log('name is ', name);
const name = undefined;
console.log('and now name is ', name);
const name1 = undefined;
const myFunc = function(){return undefined};
let template = (
<div>
{name}
{name1}
{undefined}
{myFunc()}
</div>
);
ReactDOM.render(template, document.querySelector("#root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Other Editors like codesandbox
or jsfiddle
will wrap the code in a function, hence there is no conflict with the window.name
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With