What is the primary function of a firewall?

Its primary function is to prevent accesses from untrusted (or undesired) external systems to internal systems and services, and to prevent internal users and systems to access external untrusted or undesired systems and services.

More generally, its purpose is to implement security and performance policies.

As an example, you can prevent external systems to access internal servers, as well as to prevent users to use P2P software or access social networks, for performance and security reasons.