When Maverick told Goose his quarry was too close for missiles, and he was switching to guns, the Navy was still flying the F-14 Tomcat, a twin-engine interceptor whose first flight was in 1970. Today’s newest advanced fighter jets, the F-22 and F-35, took their first flights in 1997 and 2006, respectively, and can hit targets from miles away before the enemy even sees them. So, why do they still carry internally mounted guns?
The short answer is that fighter pilots want them.

In the air war over Vietnam, American pilots took a hard lesson while engaging a skilled enemy air force with planes on par with those in the American arsenal at the time. F-4 Phantoms, while being fast and powerful, were heavy. Going up against the MiG-19 and MiG-21, they could often find themselves struggling to get out of the kill zone, unable to respond in kind because of the lack of a close-range weapon.
They needed onboard guns.

Just like in the days of the Vietnam War, many missiles have a minimum kill range. If an enemy fighter can get inside that range, even a fifth-generation fighter can find itself in deep trouble if it has no means of defending itself.
Today’s fighters may only carry enough ammunition for a few seconds’ worth of fire, but the technology in both targeting and individual rounds is far more advanced than in days gone by. A one-second burst from the onboard guns of an F-22 or F-35 is dozens of large explosive rounds on a target, more than enough to make a few passes or bring down an enemy aircraft.
The enemy could be just as skilled as any American pilot; that’s something the U.S. military can’t plan for. What they can plan for is to fight the same technology used by the U.S. and its Western allies. The Department of Defense has to assume its pilots could be going up against advanced fighters comparable to the F-22 and F-35. If a Chinese J-20 can defeat missile targeting and get in close to one of ours, the pilot will likely need to hit a target at close range, using a weapon they can point.