FACN3 / Get-Your-Shit-Together

0 stars 0 forks source link

'Coding shortcuts' shortcuts #25

Open finnhodgkin opened 7 years ago

finnhodgkin commented 7 years ago

Just a note on your shortcuts, the code you've written could be further shortened in a couple of ways, none of which are necessary, but just thought I'd raise it :smile:

Assigning the whole ternary operator, rather than each branch. This stops you from accidentally not assigning a variable on one branch:

input.checked = todo.done ? true : false;

Or use the !! operator to check whether the value is true or false and then set the var accordingly.

input.checked = !!(todo.done)

Or as an alternative (not any clearer or smaller but still worth mentioning because you'll sometimes find people using this instead of ternary, especially when there are multiple values as in the second example below) you could use and (&&) and or (||) operators to return what you want:

input.checked = todo.done && true || false;
input.checked = todo.done && anothertodo.done && true || false;

In the example above the final variable in the chain of &&s is the one that finally gets returned, and if any of the items in the chain are false then the variable after || is set


Love that you've added code examples and learning to your readme. Great job :D:D

prodionov commented 7 years ago

@finnhodgkin shame they don't have a like button on github

finnhodgkin commented 7 years ago

They do, they do!

finnhodgkin commented 7 years ago

The little face with a plus next to it is the 'reactions' button

MynahMarie commented 7 years ago

@finnhodgkin Really cool, didn't know about about the '!!' operator or about chaining multiple variables together to return a result!

Question: so could you use the || operator instead of && if you wanted to return a result if either one of the variables has a certain value?

input.checked = todo.done || anothertodo.done && true || false;

That would return true if either one of todo.done or anothertodo.done is true? (not sure about the last &&...) I know its not useful in the scope of this project but just trying to see if I understand the use of those operators correctly in that case...