How do I handle null in this code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How do I handle null in this code?

How can I make it do nothing if p is null/empty? https://code.sololearn.com/W5AR7NmwcPNV/?ref=app

7th Jul 2018, 11:05 PM
Daniel Cooper
Daniel Cooper - avatar
3 Answers
+ 1
The .match on line 9 is what nulls. Your code actually fails if the text contains no Es aswell. What you have to do is check if .match returns null. let matches = p.innerText.match(/e/gi); if(!matches){ /* that's 0 */ } else { /* not 0 */ }
7th Jul 2018, 11:08 PM
Schindlabua
Schindlabua - avatar
+ 1
Handle output null with conditional if, if(null) would be false, which in turn make it run the else conditional code. Try if(PMatch) Output.innerText = PMatch.length; else Output.innerText = 0; Or other method, use ternary Output.innerText = PMatch? PMatch.length:0; https://code.sololearn.com/WGs3u8MzY6Ga/?ref=app
8th Jul 2018, 12:26 AM
Calviղ
Calviղ - avatar
0
Can you send me the correct code? I'm new to coding and have no idea how to make it work ;-;
7th Jul 2018, 11:15 PM
Daniel Cooper
Daniel Cooper - avatar