This chapter invites people to true belief and good deeds through warning and giving glad tidings as indicated by the first two verses and the final: . . . Therefore, whoever hopes to meet his Lord should do good deeds and not join anyone in the service of his Lord (18:110). Special attention is given to refuting that God has a son by issuing a specific warning: And (so that he may) warn those who say: God has taken a son (18:4), after first issuing a general warning: . . . So that he may warn of a severe punishment from Him . . . (18:2)
This is addressed to the idolaters who believe that the angels, jinn, and spiritual reformers (muṣliḥīn) are sons of God, [and it is addressed to] the Christians who say “the Messiah is the son of God.” Perhaps it is also addressed to the Jews who attribute partners to Him, as the Qur’an mentions: And the Jews say: ʿUzayr (Ezra) is God’s son. . . (9:30).
It would not be far from the truth to say that the purpose of revealing this chapter was to narrate three amazing stories which are not mentioned anywhere else in the Qur’an apart from this chapter: the stories of the Companions of the Cave, Moses and his servant on their way to where the seas meet, and Dhū l-Qarnayn. They are narrated so inferences can be drawn from them and applied to what is mentioned in the chapter; namely, to refute the belief that God has any partner, and to inspire mindfulness of Him.
The context of the verses shows that the chapter was revealed in Mecca, except for the verse beginning with: And keep yourself patient [by being] with those who call upon their Lord (18:28); this will be explained later.