0

I am reading through some javascript code, and I have seen a lot of code that looks like this:

processMethod = processMethod || function(){};

it's usually found inside a function. I believe it's a shorthand code, but I am not sure what it does.

Does it check to see if processMethod has a value, and if it doesn't declares it as a function that can be defined later?

4
  • means if processMethod doesn't exists, just create a an empty function to prevent processMethod -- undefined error. Commented Jan 31, 2014 at 4:57
  • 1
    Sorry #Raymond Chen. I had no idea how to ask the question, or even what terms to search for before posting it. Commented Jan 31, 2014 at 4:59
  • Yeah, the important part was punctuation, which SO doesn't know how to search for. Commented Jan 31, 2014 at 5:07
  • 1
    @RaymondChen, @gdaniel: [javascript] what does "||" do Commented Jan 31, 2014 at 5:31

2 Answers 2

1

In words:

if there is no processMethod, create it empty.

|| works with booleans, so it checks if the first operand processMethod has a boolean-equivalent. If processMethod is defined and not null, the boolean-equivalent is true. If processMethod is undefined or null, the boolean-equivalent is false. In the false-case, || looks for a boolean-equivalent of the second-operand, its not null so its boolean-equivalent is true.

false || true resolves to true so processMethod becomes function(){}.

Btw function(){} is a empty function whom used to not throw a error on processMethod()

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks that makes sense. Still learning shorthand codes.
1

It essentially checks whether it exists or not. If it doesn't exist, assign it.

function doSomething(o) {
    o = o || {};
}

In the above case, it checks whether a value for o was passed. If not it assigns an empty object to it.

3 Comments

In this case doSomething(0) may unfortunately changed to {}.
Technically, but chances are if you're expecting an object you won't get 0 passed.
Correct, its also matched to the OP's concrete question.