What exacty is empty string and array used for?

Sorry this is a dumb question, but what is the role of an empty string or array used for in functions?

My thought is that the empty variable string is use to pass through the arguments/parameters kinda like a storage space to pass items through… am I wrong? for example below… what is, var answer = “”; empty string do? Thanks so much for answering!!!

function switchOfStuff(val) {
  var answer = "";
  
  switch(val){
    case 'a': answer = 'apple'; 
    break;
    case 'b': answer = 'bird'; 
    break;
    case 'c': answer = 'cat'; 
    break;
    default: answer = 'stuff';
  }
  
  return answer;  
}

You are initialising the variable so that it is a string. In this case there is not really a difference, but it is good practice, because you may have a loop that concatenate things to a string, and in that case you can’t start from an undefined value.
Same for an empty array. You can’t push to an undefined value, you need for the variable to be of tipe array

1 Like

I still dont get it… what is used for???

In lot of cases you want to initialise a variable to a certain specific values of the same types you expect them to be later.

This increase readability since you know upfront what your code expects and what type it is, and your future self as well will be grateful you did it.

Also doing this reduce the chances of bugs and type errors since you are always clear and upfront about the data you expect.

In this specific case the variable answer is initialised as an empty string, then later populated / manipulated and returned.
Think of it as a mean to keep your code consistent ad tide.

1 Like

@ainneo FYI - If you did not want to use a default case in the switch statement, you could simply initialize answer as “stuff” before the switch statement.

var answer = "stuff";

In other words, you can initialize a variable to a value which if no other value is ever assigned to it, the function would return this default value.

1 Like