The city's name is derived via French and Catalan Alger from the Arabic name al-Jazāʾir (الجزائر), "The Islands". This name refers to the four former islands which lay off the city's coast before becoming part of the mainland in 1525. Al-Jazāʾir is itself a truncated form of the city's older name Jazaʾir Banī Mazghanna (جزائر بني مزغانة), "The Islands of the Banu Mazghanna", used by early medieval geographers such as Muhammad al-Idrisi and Yaqut al-Hamawi. In classical antiquity, the ancient Greeks knew the town as Ikósion (Ancient Greek: Ἰκόσιον), which was Latinized as Icosium under Roman rule. The Greeks explained the name as coming from their word for "twenty" (εἴκοσι, eíkosi), supposedly because it had been founded by 20 companions of Hercules when he visited the Atlas Mountains during his labors. Algiers is also known as el-Behdja (البهجة, "The Joyous") or "Algiers the White" (French: Alger la Blanche) for its whitewashed buildings.
The city's earliest history was as a small port in Carthage where Phoenicians were trading with other Mediterraneans. After the Punic Wars, the Roman Republic eventually took over administration of the town, which they called Icosium. Its ruins now form part of the modern city's marine quarter, with the Rue de la Marine following a former Roman road. Roman cemeteries existed near Bab-el-Oued and Bab Azoun. The city was given Latin rights by the emperor Vespasian. The bishops of Icosium are mentioned as late as the 5th century, but the ancient town fell into obscurity during the Muslim conquest of the Maghreb. The present city was founded in 944 by Buluggin ibn Ziri, the founder of the Berber Zirid dynasty. He had built his own house and a Sanhaja center at Ashir in 935 just south of Algiers. Although the Zirid dynasty was overthrown by Roger II of Sicily in 1148, the Zirids had already lost control of Algiers to their cousins the Hammadids in 1014. The city was wrested from the Hammadids by the Almohad Caliphate in 1159, and in the 13th century came under the dominion of the Ziyanid sultans of the Kingdom of Tlemcen. Nominally part of the sultanate of Tlemcen, Algiers had a large measure of independence under Thaaliba amirs of its own due to Oran being the chief seaport of the Ziyanids. The Peñón of Algiers, an islet in front of Algiers harbour, had been occupied by the Spaniards as early as 1302. Thereafter, a considerable amount of trade began to flow between Algiers and Spain. However, Algiers continued to be of comparatively little importance until after the expulsion of the Moors from Spain, many of whom sought asylum in the city. In 1510, following their occupation of Oran and other towns on the coast of Africa, the Spaniards fortified the islet of Peñon and imposed a levy intended to suppress the Barbary pirates.