Mainly for compatibility.
Modern browsers don't need it anymore. See this HTML file that does not have a !DOCTYPE:
<p>hello</p>
The browser automatically inserts the !DOCTYPE.
But that's only in modern browsers.
In IE8, some css properties only have functionality when the doctype is stated.
So, if you don't need to support ancient relic browsers, you don't need it. But it has become a programmer custom!
———
Update:
The doctype used to require a DTD URL. The DTD defines all the elements in the document. If you are using the HTML 4.01 DTD, HTML 5 elements will not work.
But it is not all sunshine and butterflies.
Some features will break. Without a DOCTYPE, the green square fills up 50% of the width:
div {
width:50%;
background-color:#00ff00;
}
<div>div</div>
But with one:
div {
width:50%;
background-color:#00ff00;
}
<!DOCTYPE html>
<div></div>
However, stack snippets automatically adds a !DOCTYPE, so you can't see it here.