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 trialKirby Abogaa
3,058 Pointsvariables
okay so im a bit confused about this...
what is the difference between the 2 declarations:
var example ;
and
var example = ' ' ;
and when do you use each of them...
any info is appreciated..
Cheers!
3 Answers
Parker Busswood
20,207 PointsHey Kirby!
Here's the short version:
var example; <- example = undefined
var example = "";
When you instantiate the variable without assigning a value, the value of that variable is undefined
. When you set the variable to an empty string (""
), this is actually defining a value for the variable which is just the empty string.
If you open the console in your browser (for me in Chrome, right-click, Inspect Element, go to Console tab), you can type JavaScript there and see immediate feedback. If you type var example;
, you'll see what I'm talking about where it returns undefined.
Hope that helps!
Parker
Dan Oswalt
23,438 PointsBoth are valid, the top will simply have a value of 'undefined', and the bottom will be an empty string. If you aren't going to be using the initial value, and you aren't going to be testing the type the variable with the 'typeof' operator or something, then declaring it without a value is fine.
Leaving a variable undeclared is okay in javascript since we don't have to cast a variable as a type. Usually when you see it, it just means the coder plans to use it later without littering the script with 'var'.
For example:
var a, b, c;
//instead of:
var a;
var b;
var c;
//or
var a = 0;
var b = "";
var c = [];
Kirby Abogaa
3,058 PointsThanks guys! Its clear now.
Thumbs up to you both.