Skip to content
the poor coder

how to check if the const is jsx

Poor Man
Published
Reading time
1 min read

When checking if a const is JSX, the most reliable way is to check the type of the const. JSX is a special type of Javascript syntax, so if the const is of type JSX then you can be sure that it is JSX. To check the type of the const, you can use the typeof operator in Javascript.

Text

const myConst = 'This is a const';

// Check the type of the const
console.log(typeof myConst);
// Outputs: 'string'

If the typeof the const is 'object' then it is likely to be JSX. When JSX is compiled by a transpiler such as Babel, it is converted into a React.createElement call. React.createElement calls return a data type of object.

Text

const myJSX = This is JSX;

// Check the type of the const
console.log(typeof myJSX);
// Outputs: 'object'

To be absolutely certain that the const is JSX, you can also check the constructor type of the const. The constructor type of JSX will be the built-in React.Element constructor.

Text

const myJSX = This is JSX;

// Check the constructor type of the const
console.log(myJSX.constructor);
// Outputs: ƒ () { [native code] }

If you are using a transpiler such as Babel, you can also check the compiled code to see if it is a React.createElement call. This will confirm whether the const is JSX or not.

Text

const myJSX = This is JSX;

// Check the compiled code
console.log(myJSX);
// Outputs: React.createElement("div", null, "This is JSX")

By using the typeof operator and checking the constructor type, you can reliably check if a const is JSX.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC