Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Loops, Arrays and Objects Tracking Data Using Objects The Student Record Search Challenge Solution

Clarification on declaring emtpy string..

Hi everybody,

I continue to have trouble to understand why declaring an empty string. It's a difficult concept to understand for me and I think this is a very important step to understand.

Please can you explain me better this concept? Why to use it and in which case?

Thanks everybody for the help!!!

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

In many programming languages you have to explicitly tell the compiler what kind of data is going to belong to a variable. If you don't, your code won't compile. Javascript has something called type inference. Which is why all variables are created the same way. It makes a best guess as to what the data type is based on how it's being used. But sometimes there can be a little ambiguity (especially if your'e rereading yours or others' code) as to what kind of data a specific variable is supposed to contain. It's (as I understand it) considered good practice to initialize a variable that's going to hold a string later with an empty string so that the interpreter (and yourself) know that this variable will hold our string later.

jsdevtom
jsdevtom
16,963 Points

w3's page on js best practices says this:

It is a good coding practice to initialize variables when you declare them.

This will:

  • Give cleaner code
  • Provide a single place to initialize variables
  • Avoid undefined values
// Declare and initiate at the beginning
var firstName = "",
    lastName = "",
    price = 0,
    discount = 0,
    fullPrice = 0,
    myArray = [],
    myObject = {};

Note Initializing variables provides an idea of the intended use (and intended data type).