Skip to content
Advertisement

return boolean value for a custom function

I am comparing key elements in a list with dictionary keys

JavaScript

I wrote a custom function as follows

JavaScript

I want to execute the other part of my code, only if the function executes without any errors. I dont understand how to specify a return value for the function and execute my code based on the return value

I am trying this : calling my function first

JavaScript

Is this the right way to do?

Advertisement

Answer

First things first, I see a couple of issues

1. There is an issue with your eval condition (you are missing an else)

JavaScript

2. Your function is not returning True or False AND the not in operator isn’t used correctly when checking for ‘https’

JavaScript

Moving on…

I am a bit unclear as to what you’re referring to as the “right way”

I’ll take a stab at it and assume you are referring to reducing the complexity and/or lines of code in your sample…

You may try to use the following “optimizations”

Changing your function to use list comprehensions

NOTE: I did change the name of the “body” function param to “body_str” as it shadowed the body variable from the outer scope. Please avoid this as a rule of thumb

JavaScript

The following line essentially returns a new list of elements that match your if condition, it then uses the len operation to count the number of elements that matched the said condition

JavaScript

Changing your evaluation

One possibility (I would personally use this)

JavaScript

Another possibility is to get rid of temporary variable assignment altogether – reduces readability though

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement