Try/Catch Functions: False versus Falsy

本秂侑毒 提交于 2019-12-11 08:16:38

问题


This is a petty question that will make you cringe, but I'm still curious.

Is it slightly more efficient (for if/then logic) to evaluate an explicit false over falsy values such a null or undefined?

When I try/catch inside of a function, with the intent of recovering from an unimportant (yet) application-halting error, I typically returned undefined when the try portion cannot not succeed.

However, below I'm returning false instead of undefined:

var parseJSON = function(jsonString)
{
	try
	{
		var obj = JSON.parse(jsonString);
		if (obj && typeof obj === "object")
		{
			return obj;
		}
	}
	catch (error)
	{
		console.log(`🐛 JSON error, but no need to halt.`);
	}
	return false; //false will not require coercion later, right?
};

let testInput = `This is NOT JSON!`;


if (parseJSON(testInput))
{
	console.log("Success, JSON was parsed");
}
else
{
	console.log("Is it faster to get here from an explicit false than a falsy value?")
}

I totally realize that the differences are negligible. Yet, you do have to choose, so why not choose the fastest choice if there is one. Instead of just concluding it doesn't matter, I'd like to give this topic a moment of consideration once and for all.

来源:https://stackoverflow.com/questions/58965352/try-catch-functions-false-versus-falsy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!