Namenode is the component that holds all the records (metadata) of files stored in hdfs. It's holds the tree structure of all files stored on the cluster and keeps track of these files.
The common practice is to format only the namenode. When you format the namenode, the metadata related to the data stored in the hdfs is lost but in fact, the data is still present in the datanode. When the namenode is formatted, the namenode thinks that there is no data in the hdfs.
It is not a "must-do" step to format the datanode. Formatting the namenode will be just fine.
If you want to format the datanode, you can do it manually using the rmr option. Refer to the below syntax:
hadoop fs -rmr /path/to/hdfs