If Else Question For Javascript Coders

I know this code works as I use it quite a bit but I was wondering if there is a more elegant way of writing it ?

if (app.activeDocument.activeLayers[0].kind !== "curves") {
 } else {
   //run this bit of code


Depends on that bit of code you want to run

Eg. 1

if (app.activeDocument.activeLayers[0].kind === "curves") {
   //run this bit of code

Eg. 2

app.activeDocument.activeLayers[0].kind === "curves" && someSingleCall()

Also you might want to check if you have active document and layer


And you should consider using constants to check layer kind

How would you best use Constants

@IanBarber, is my answer about constants really a solution to your original question about if/else? :slight_smile: It’s just an advice to replace strings with constants, which doesn’t have much to do with if/else

Its helps me become more efficient with coding which is important to me

I think the if/else statement is fine as is. However, if you only need to run code if a condition is met and not run code if it isn’t met then just using if without else is easiest.

I personally prefer this style:

function something(layer){
  if (layer.kind !== "curves") { return;}
  // more code here

And I do this because I want to have easily readable code. Instead of nesting several if statements inside each other and having deeply nested code. I prefer to return as soon as possible. If you do write it often like this then you get used to it and is good for me to use and understand :slight_smile:


Totally agree with @Jarda here. That’s why I gave couple of examples. It also depends where that if() is and what’s the context. As Jarda, in a function I would also use an early return

Something else I noticed in the original sample – you might want to be more descriptive wrt what you’re doing. I might do this:

const firstActiveLayer = app.activeDocument.activeLayers[0];
if (firstActiveLayer.kind !== constants.LayerKind.CURVES) return;

Which you use may also depend on context – i.e., if you’re in a React view, you may be more likely to use the (condition) && (result) form, or even a ternary form (:?):

{ firstActiveLayer === constants.LayerKind.CURVES && <div>Curves</div> }


{ firstActiveLayer.kind === constants.LayerKind.CURVES ? <CurveEditor/> : <Error>Select a curves layer first</Error> }
1 Like