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 trialAhad Zeb
Full Stack JavaScript Techdegree Student 108 PointsWhen declaring a variable without giving it a value, why don't we use the 'var' keyword before typing in the type?
This confuses me so I apologise if it's a dumb question but why don't we have to use 'var' before 'int' when declaring a variable?
1 Answer
Steven Parker
231,248 PointsBoth "var" and "int" declare a variable, but they would never both be used in the same declaration.
"Var" can only be used when you also initialize it because the compiler examines the value being assigned to determine what type of variable to create. On the other hand, "int" declares the type explicitly, so it can be used with or without initialization.
A X
12,842 PointsA X
12,842 PointsHi Steven, So let me see if my analogy works here (and if I'm understanding the concept too!) -
If I point to an object in the real world and say, "Hey Steven can you bring me that thing?" Although technically correct, it's not very specific, much like var. So var is roughly equivalent to the English word thing. If I said, "Hey Steven can you bring me that orange?" You now know what type of thing I'm talking about & makes it easier for you to fulfill my request...or in C# : str thing = orange .
So just as it would be weird to say: "Hey Steven can you bring me that thing orange?", we don't want to say var str thing = orange.