3

I've always used the following syntax to ensure that the input variable isn't null.

function f(input){
  if(input === null)
    input = "";
  ...
}

Lately, I noticed that it's shorter to express it as follows.

function f(input){
  input = input ? input : "";
  ...
}

But also, I've seen this syntax.

function f(input){
  input = input || "";
  ...
}
  1. Are those equivalent (not in what they do but in how they do it)?
  2. Which is most recommended (readability etc.)?

Note that I'll be strictly working with inputs of strings such that it's either valid one or null (not provided at all). If I'd like to extend the protection to include other types, what additional issues should I take into consideration?

3
  • 2
    Another one - input || (input = ""); Commented Jun 22, 2013 at 16:00
  • @VitaliyPetrychuk Would it be faster? Also - I'd expect return or *input = * in front of your suggestion. Am I mistaken? Commented Jun 22, 2013 at 16:01
  • I do not think that this is the code you have to optimise :) Commented Jun 22, 2013 at 16:08

1 Answer 1

3

First, note that they aren't all the same. #2 and #3 have precisely the same result: unless input is truthy, set it to an empty string. #1 means says "unless input is null, set it to an empty string. So if false was provided, input would be false in #1 but '' in #2 and #3.

If nothing was provided to #1, (i.e. f(), input would be undefined, because that is the value that is passed when a parameter is missing, not null. One of these would fix this:

if(input === undefined)
if(input == null)

Otherwise, yes, they are functionally equivalent. For me, the best way to write it would be

input = input || "";

That is my preferred style. It may be yours; it may not. But, above all, be consistent.

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

2 Comments

Also, since the OP was worried about speed in his comments, your preferred style is faster
@Nile Though the difference is what might optimistically be called "infinitesimal".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.