I have a very basic question that I don’t know that exact answer to.
Is there a set of rules for this?
When do we need to declare a variable = 0 or " "
When is it ok (if ever) to just declare a variable: var total;
For example:
var total; vs var total = 0; // i know this is for numbers
var name vs var name = “”; // i know this is for strings
Thanks again for answer all of my questions on here!!! I don’t have another teacher to talk to so this is very helpful *
Initialize a variable var x = 0;
if you intend to use x
before you assign a value or there is a chance you will use it before you assign a value.
Just declare a variable var x;
if there is no way you will use it before you assign it a value or if you are using the value undefined
to tell you something.
Use a number var x = 0;
if you are going to do mathematical operations on it.
Use a string var x = "";
if you are going to do string operations on it.
Go to unit 4 lesson 11 Level 3 The Quote Maker. Look at the exemplar given. Variables are initialized. For example, line 3 is var quote = "";
That is initialized to an empty string because we expect quote
to be a string. Line 6 is var fontSize = 24;
because we expect fontSize
to be a number.
The reason we initialize those variables is that when we look at the calls to onEvent
each call only sets one of the variables prior to calling updateScreen();
which expects those variables to have values other than undefined
.
Now look at this code Code.org - App Lab. None of the variables are initialized. That is because I always call getScreenProperties();
before updating the screen. I don’t need them to have initial values because I always get them values before I use them.
Thank you so very much I appreciate you taking time to help me! These examples are very useful! Take care! ~michelle