1

I'm working with an API call using axios and getting back some JSON in a response. I have a variable that will hold the result of one of the JSON object's values, in this case a string:

let first_name = "";
//later on..
first_name = response.data.firstName;

I had my hand slapped because I had initialized first_name to an empty string instead of null and I'm not sure why-- the person doing the code review muttered something about best practices and didn't really answer me.

My question-- if I'm checking for an empty string instead of null when using first_name later on, does it matter what I initialized it to? Is there a javascript best practice or optimization I'm missing out on by setting the variable to an empty string?

[edit]

Some good discussion in the comments about how I'm using first_name later on in the code. Let me elaborate.

I don't want to do a code dump, so let me put it this way, after first_name has been assigned I check to make sure it's neither an empty string or null before using it. What I'm interested in here is whether what I did is wrong or inefficient in javascript terms, or 'worse' than assigning it as a null. I assigned it as a string as a mnemonic that it should be a string value if all goes well.

larryq
  • 15,713
  • 38
  • 121
  • 190
  • 3
    no, but `let first_name` is shorter (and assigns `undefined`) ... note: if someone told you `let first_name = null` in this situation is preferred to `let first_name = ""`, then he knows less about it than you :p – Jaromanda X Oct 01 '19 at 04:43
  • 6
    Initializing it to *anything* when it doesn't contain a meaningful value is weird - readers of your code will probably think "Why is this being explicitly assigned to a particular value?". Check `undefined` instead - or, even better, only declare the variable when it's assigned to for the first time, with `const` – CertainPerformance Oct 01 '19 at 04:44
  • 1
    @CertainPerformance - `const` would mean it can't be assigned to later - and clearly the code wants to do that – Jaromanda X Oct 01 '19 at 04:44
  • `response.data.firstName` what are the possible values this can hold ? – Code Maniac Oct 01 '19 at 04:45
  • I’d also agree that best practice is not initializing to values that are intended to never matter. `let first_name;`. Although maybe show more context? – Ry- Oct 01 '19 at 04:46
  • @CodeManiac - why would that matter regarding how `first_name` is declared? – Jaromanda X Oct 01 '19 at 04:46
  • @JaromandaX It's not so clear, there's not enough code in the question to tell. If OP only assigns to it inside the block that uses `response` (once), `const` can be used. – CertainPerformance Oct 01 '19 at 04:46
  • 1
    @CertainPerformance - I see what you mean, i.e. declare the variable where it is used – Jaromanda X Oct 01 '19 at 04:47
  • @JaromandaX `I had initialized first_name to an empty string instead of null` i am trying to see a reason why is person who was reviewing insisted on using `null`, if there is case `response.data.firstName` can be empty string and can't be null, then his statement makes sense – Code Maniac Oct 01 '19 at 04:48
  • 1
    `the person doing the code review muttered something about best practices` - and knows nothing ... let first_name = null; is equally "bad" – Jaromanda X Oct 01 '19 at 04:49
  • The reason I declared it as an empty string is because it's supposed to have a string value (first name) when it's finally assigned; it's a hint or mnemonic, sort of like declaring it as a string in Java. That's the thought at least. – larryq Oct 01 '19 at 04:49
  • @CodeManiac - as long as the assignment is *conditional* of course – Jaromanda X Oct 01 '19 at 04:50
  • 1
    @larryq - it's obvious you haven't shown enough code ... is the "later" code conditional? i.e. `if (some condition) first_name = response.data.firstName;` ... is there other code accessing `first_name` that specifically tests for it's value to determine if it has been assigned or not? - two lines of code make it difficult to really answer your query, which is probably why you've received comments but no answers :p – Jaromanda X Oct 01 '19 at 04:52
  • @JaromandaX the 'assignment' code is actually being done in a callback from axios-- `axios.get('api_endpoint').then(response){first_name = response.data.firstName}....` – larryq Oct 01 '19 at 04:54
  • If however, as you say, you've assigned an empty string merely as a "hint" to its final content, then, as far as I'm concerned, `let first_name = "";` makes more sense than this hand slapper who thinks `let first_name = null;` is in some way "better" and you have my permission to slap him across the face :p – Jaromanda X Oct 01 '19 at 04:55
  • that doesn't help either @larryq - because there's no way for any of us to know everywhere `first_name` is being used in the code – Jaromanda X Oct 01 '19 at 04:55
  • I'll edit the question to help. – larryq Oct 01 '19 at 04:56
  • 1
    @larryq _"`.then(response){first_name = response.data.firstName}`"_ this looks like the classic [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Phil Oct 01 '19 at 04:57
  • 8
    _"the person doing the code review muttered something about best practices and didn't really answer me"_ one of the best thing about code reviews is the ability to mentor and teach. Ask your reviewer to explain without muttering – Phil Oct 01 '19 at 05:03
  • I think the only difference is, null means value is not available and empty string is still a valid value. So if you code has kind of validation where null/empty string/undefined is not allowed, I think initialising to empty string is good. Ask your code reviewer what are the implications of assigning to empty string than undefined :) – Sagar Agrawal Oct 01 '19 at 05:15

4 Answers4

7

Is there a technical issue with initializing a JavaScript variable to an empty string instead of null?

That depends on the context, but there is no immediate technical issue. From a pure technical perspective, it doesn't matter whether we check first_name === null, first_name === "", first_name === undefined or just !first_name.

Note that all of this is very specific to JavaScript, as many other languages either don't have Null or use a completely other model to indicate the absence of values.

null versus string

Let us analyse the issue a little bit further to understand the reasoning of your reviewer.

null is not a string

In the end first_name is a result of some computation that returns a string. If that string can be the empty string "", it's reasonable to use null, as null !== "". We can check the absence of a valid value without additional first_name_set flags or similar.

If we use null, then we never pool our initial value from the domain of valid values, which can be a boon in debugging, error handling and sanity checks.

"" might not ever be valid

If, however, first_name will never be the empty string, the empty string might be a valid candidate for our invalid data.

Best practices must be explained

But this explanation for null is something one can up with. The reasoning of your reviewer on the other hand is in their mindset. If it is best practice according to them, it might be "best practice" throughout the company. That doesn't necessarily mean that it's also best practice in the real world, as some weird misconceptions can have a long tradition in companies with a lot of self-taught programmers. Your best practice as a reviewed would be to question their reasoning.

A good code review improves the reviewed code, a better code review teaches better practices, but the best code reviews improve the overall code base and teach both sides.

Remark on initialization

That being said both variants employ additional pressure on the developer: we're forced to check whether our value is valid. A better solution (if possible) is to get rid of the invalid initialization and only initialize with a correct value. async and await can enable us to do so in callback situations.

Zeta
  • 103,620
  • 13
  • 194
  • 236
4

I think your reviewer is thinking of:

  • Using null states no data is available.
  • Using empty string states data is available (returned from api).

I also agree with that using null will be best practice in that sense.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
  • 2
    I agree enough to upvote, though it holds true for most other languages much more strongly than for JavaScript, which distinguishes `null` and `undefined`. – Amadan Oct 01 '19 at 05:14
0

I do understand that javascript supports all these as a falsy values

  • false
  • 0 (zero)
  • “” (empty string)
  • null
  • undefined
  • NaN (Not A Number)

It directly indicates that null and empty string both are false. All is depending on the use case. According to your use case, it is okay to use an empty string. But still, I suggest using null for these better improvements.

  • Null is a best practice to show there is no data available.
  • An empty string indicates empty data is provided while null indicates no data is provided.
  • Empty data can end up you to produce buggy code by providing access to the class members while data returned as null comes under the null exception and prevent you from the buggy code.
Shraddha Goel
  • 869
  • 7
  • 18
0

Initializing first_name with a value makes only sense if there is a possibility that first_name = response.data.firstName won't be executed and code after that reads from first_name:

let first_name;

if( ... ) {
   first_name = response.data.firstName;
}

// ...

doSomething(first_name)

or

let first_name;

try {
   // some code
   first_name = response.data.firstName;
} catch(err) {
}

// ...

doSomething(first_name)

Because then you could ensure some default values.

But if there is nothing in between let first_name; and first_name = response.data.firstName; then initializing of first_name does not make sense, and declaring it that early does not make sense either.

So it should be:

let first_name = response.data.firstName;
// ...
doSomething(first_name)

Moving all declaration to the beginning of the function is a relic from the time where let and const were not available, because the engine/compiler would not warn you about:

function foo() {
   console.log(bar)

   // ...

   var bar = 2; 
}
t.niese
  • 39,256
  • 9
  • 74
  • 101