How can I get the return from an If statement whilst testing the condition?

Viewed 35

Hey there out of curiosity this is a problem I've run into several times as a noob programmer. On occasion I have to write a line like this string.match(regExp) but I may then store that match, all good so far let matchedString = string.match(regExp), but I don't want to store a value if no match is found (this problem also applies to situations outside of strings or regular expressions).

I have to use an if statement to check the result of that line then: if(string.match(regExp),but then I have to write code that seems convoluted to store the value; if(string.match(regExp)) matchedString = string.match(regExp); needlessly repeating the initial function. Is there a workaround to this? Or a simple general solution that I've missed?

2 Answers

If you don't want to store the value,

let matchedString = string.match(regExp) || null;

As anyhow you are going to store a matched results in a variable, You have to declare that variable somewhere either globally or locally. At that time compiler automatically allocates memory for it. This is known as compile time memory allocation or static memory allocation.

Now coming to your question - By default, If no matches happen String.match() will return null and as variable already taken the memory so there is no harm to assign null to it if there is no matches happen.

Live Demo :

var str = 'alpha';

const res = str.match(/[0-9]/g);

console.log(res); // null

Related