Why did Allah create the universe?
Allah the Almighty, Who is the Maker of the universe and of all beings in it, created the universe for very significant purposes. Quran informs this as follows:
"Not for (idle) sport did we create the heavens and the earth and all that is between." (Anbiyya Surah, 21:16)
"Not without purpose did we create heaven and earth and all between" (Sa Surah, 38:27)
All beings glorify and magnify the Exalted Creator with their languages. They fulfill the tasks with a pleasure and enthusiasm, which are assigned to them. For example, the sun, without falling behind even a second, moves around the orbit, which has been drawn for it. Rivers enthusiastically flow into seas. Animals, which have been given under the command of man, serve him with an absolute obedience.
Besides, if the universe had not been created, the never-ending perfection and beauty of the names and attributes of Allah Almighty would have never been known. This would have only been known by Allah (SWT). By manifesting the spiritual beauties of His names and attributes, Allah Almighty, besides beholding His own Beauty and Perfection on His own works, also wished to give a share to angels, man, and jinn from this honor and bestowal.
Regarding the question of whether to create the beings or not to, Allah (SWT) made His Divine preference for creation, and this preference has become an interminable mercy for all creatures. Or else it is unthinkable that Allahs, one of Whose names is Samed (everything is in need of Him but He is in need of nothing), creation of this universe stems from a necessity.