0

I have a colleague that instantiates all his variables with empty string for their default value. That variable later could have an array or object assigned to it an although that might be known he still assigns empty string as default. Ex.

function getAllCars(){
  var listOfCars = ['bmw','fiat','reno'];
  return listOfCars;
}

function getAnyCar(){
  var cars = "";
  cars = getAllCars();
  var car = cars.slice(0,1);
  return car;
}

TL;DR: What should a good practice for defining cars be

  1. var cars;
  2. var cars = [];
  3. var cars = "";

I am trying to explain to him that if you know that the variable cars is going to be used to hold an array you should define it with an empty array.

He argues that he knows that variable is 100% going to be assigned an array down the line i.e cars = getAllCars(); so it doesn't matter. In a small function such a thing may be visible but I believe it to be bad practice.

2
  • 2
    The better practice would be never have uninitialized objects in your code and generally do const cars = getAllCars(). Dealing with unclean state is pretty hard. This is subjective though. Commented Aug 10, 2017 at 8:58
  • @BenjaminGruenbaum thanks for the talk that you linked. Seems interesting. Will save it to watch later. Commented Aug 11, 2017 at 6:36

3 Answers 3

2

It is indeed bad practice to have a variable change its type often to unrelated types. Javascript already has two perfectly fine values to mean "no value": undefined and null. What you read into the difference is mostly up to you, but both are much more appropriate than an empty string. The mostly natural way would be the default undefined:

var cars;

This reserves the variable name in the scope, but does not assign it a value. That is the clearest way to express what this code is actually doing.

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

Comments

1

JS is dynamically typed and allows changing type at run-time, but this makes your code confusing.

According to good practices (if not best), it's suggested to initialize variable when declaring it. This gives cleaner code (clear indication that cars is an array) and avoids undefined values.

var cars = [];

On the other hand, some devs prefer to just declare and not initialize until necessary. So this is also fine.

var cars;

I think which one to follow of these two is matter of opinion or perhaps choice. But for sure, initializing var cars = "" does not make sense at all in your example.

Comments

0

Defining an empty string as a default value is a pretty bad practice. I would use

var cars = getAllCars();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.