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 Basics (Retired) Making Decisions with Conditional Statements Boolean Values

Do we always have to assign an initial value to a variable when defining them?

Can we define a variable without an initial value and asign a value when needed? Or does this pose problems in JS?

var myVariable;

At a later point in the programm:

myVariable = true;

2 Answers

Yes this is possible, it doesn't pose a problem in JS as long as you know yourself what the variables value or type should be and what actions you may want to take if the value cannot be updated.

In this case, the value of the variable will just be undefined.

The link below is useful for understanding this a bit further quickly:

https://github.com/getify/You-Dont-Know-JS/blob/master/up%20%26%20going/ch2.md#values--types

Thank you for the resource! So if you wanna be sure to use the right type later on, you better asign a value, because the variable itself doesn't ever have a type like in C#, that's good to know.

With var you could just keep setting it to any type and value that you want.

If you are familiar with a language like C#, then you could also look at TypeScript. I have started to use it recently and really like it, so you may have an advantage here making that jump as it may feel more at home to you.

Other than that, let and const instead of var, could offer a bit more specificity on how you want the variable to behave.

https://github.com/getify/You-Dont-Know-JS/blob/master/es6%20%26%20beyond/ch2.md#let-declarations

https://github.com/getify/You-Dont-Know-JS/blob/master/es6%20%26%20beyond/ch2.md#const-declarations

Hope this helps.