All perfect praise be to Allaah, The Lord of the worlds. I testify that there is none worthy of worship except Allaah and that Muhammad, sallallaahu ‘alayhi wa sallam, is His slave and Messenger.
It has been narrated that the Prophet, sallallaahu ‘alayhi wa sallam, said, "If you were attacked at night, let your war cry be Haa-Meem, la yunsaroon (which means: Haa-Meem, they will not attain victory)." [Sunan Abu Daawood]
Another version of the hadeeth reads, "If the enemy attacks you at night, say: Haa-Meem, la yunsaroon."
The following has been narrated on the authority of Az-Zubayr ibn Suraakh: "Mus'ab ibn Az-Zubayr said to us while we were about to fight against Al-Mukhtaar (ibn 'Ubayd), who falsely claimed to be a Prophet, 'Let your war cry be 'Haa-Meem, la yunsaroon' for it was the war cry of the Prophet, sallallaahu ‘alayhi wa sallam." [Musannaf Ibn Abu Shaybah]
We did not find any statement for the scholars stating that this phrase should be recited when one is faced with danger. They only said that it was the war cry of the Companions. The benefit of the war cry was to enable them to identify one another on the battlefield. Al-Buhooti wrote:
"Each group should have a war cry to call one another on the battlefield, based on what Salamah ibn Al-Akwa’ reported: 'We went on a military expedition with Abu Bakr in the lifetime of the Prophet, sallallaahu ‘alayhi wa sallam, and our war cry was 'Amit, Amit.' (Which means: Put to death, Put to death.)' [Abu Daawood] Another reported war cry was: Haa-Meem, la yunsaroon. The rationale behind using a war cry was to be able to locate each other on the battlefield, or seek help, or to prevent that they mistakenly kill one another." [Kashshaaf Al-Qinaa‘]
Allaah knows best.