deebs
deebs

Reputation: 23

Understanding use of empty string in Javascript

I am taking a Javascript class and we recently had an exercise that I am having a hard time understanding how the solution actually works.

The question is this:

Create a variable n and assign it an integer. Code a while loop that builds as a single string, the numbers 1 through n, separated by commas How can we make sure not to have a comma after the last number? e.g., for n = 9 print "1, 2, 3, 4, 5, 6, 7, 8, 9"

I got so far as to be able to list each number with commas but they were not on the same line. My instructor tried to walk me through the solution but her explanation isn't working for me. Is there anyone that can explain to me why using a variable with an empty string provides the solution. This is what she showed me as the correct solution (I am ignoring the not showing last comma part for right now):

var n = 1
var tr = ""

while (n <= 9) {
tr = tr + n + "," 
console.log (tr)
n++
}

I don't understand how an empty string helps accomplish this outcome. Anyone particularly good at analogies or explaining this logic?

Upvotes: 0

Views: 2221

Answers (5)

Mark Schultheiss
Mark Schultheiss

Reputation: 34227

Since this is an "instructional" answer, it will be longer than otherwise.

First off, you must define your tr variable If you fail to define tr here you get an "Uncaught ReferenceError: tr is not defined" if used directly or undesired results if used in a string for example.

var tr;
alert(tr);//errors

Uncaught errors cause JavaScript to stop processing at the point of error Example of bad declaration (no value) for our use here:

var tr; //done like this it is undefined (tr === undefined)
alert(typeof tr === "undefined") // alerts true
// now if we add a string to that we get:
tr = tr + "hi"; // returns string "undefinedhi" in tr by doing (undefined + "hi")

var tr = "";
alert(typeof tr === "string") // returns true
tr = tr + "hi" // returns string "hi" by doing ("" + "hi")

Thus we have to define our variable prior to use and assign an empty string to it (we DO want to create a string)

In JavaScript, the + is used for both addition of numbers as well as string concatenation.

You COULD use the concat function of the string prototype.

String.prototype.concat()

The concat() function combines the text from one or more strings and returns a new string. Changes to the text in one string do not affect the other string.

var oldstring = "Howdy";
var otherstring = "Freddy";
// combine 4 strings:
var newstring = oldstring.concat(otherstring, "End", " Is near");

This returns the text value of "HowdyFreddyEnd Is near" in newstring, oldstring still has "Freddy" as its value.

Note it is STRONGLY recommended to use the + and += instead of concat() for performance reasons, you simply have to understand the processing using those as described here.

Loops

Your requirement is to use n as a value and process from that value down to 1.

Negative while loop:

Negative while loops are faster than positive ones especially in older browsers, less so in more modern ones.

Here we use another feature of JavaScript where other types can be used as a Boolean. For numbers, any value that is positive will return true, 0 will return false. As long as we KNOW the value will start with a positive integer, we can simply use it (the number) and then process it in a while loop example: while (n). Note that -1 will return true as a Boolean value. For a single integer, we can simply use it, for other numbers we can coerce it into a Boolean value.

Some examples:

if (0) // returns false
if (-1) // returns true
if (1) // returns true
if (2 - 1) // returns true (1 value)
if (1-1) // returns false (value 0)
if (0 + "") // returns true (value "0" as a string) non-empty strings are true
if(n) // returns true for non zero values of n
if (n > 0) // returns true for positive values of n
if (n >= 1) //true for positive values of n (less clear than previous in my opinion)
if (n > -1 && n != 0) // same thing just more complicated

If we do NOT know if our value starts with a positive integer, we can check for that explicitly:

if(n > 0)

Why cover all that? your while (n <= 9) { will fail if n is 0 or negative to start with and has a hard coded value of 9 which is not typical.

Otherwise, we can simply use values starting with positive integers:

Example:

var n = 23;
var tr = ""; // done like this it is an empty string (tr === "")
while (n) {
  tr = n + "," + tr;// put next lower value at the start
  n--;
}
tr = tr.slice(0, -1); // remove last comma

Increment while loop

Process using a ++ requires use of a second variable

var n = 23;
var i = 1;
var tr = "";
while (i <= n) {
  tr = tr + i + ",";
  i++
}
tr = tr.slice(0, -1); // remove last comma

Use += instead of tr = tr + i + ",";

var n = 23;
var i = 1;
var tr = "";
while (i <= n) {
  tr += i + ",";
  i++
}
tr = tr.slice(0, -1); // remove last comma

Note on slice

tr = tr.slice(0, -1);

is the same as

tr = tr.slice(0, tr.length -1); 

Upvotes: 0

Dan
Dan

Reputation: 3020

I don't understand how an empty string helps accomplish this outcome.

Javascript handles different 'types' of values differently.

If you were to have for example console.log(3 + 3), the output would be 6.

If you console.log('the ' + 'dog') the output would be "the dog".

So what happens in this case: console.log('the' + 3)?

Since it is impossible to add a string to a number, it is assumed, that the number should be converted to a string, and the output is "the3".

Ok, so what about this case: console.log('' + 1 + 2)? The same logic is applied, and the result is "12". So an empty string forces Javascript to interpret the operator + as string concatenation (joining strings), rather than numerical addition.

Finally, and importantly, concatenating undefined would result in NaN, so it is important that you don't just declare your variable, but that you set it to an empty string ''.

I got so far as to be able to list each number with commas but they were not on the same line

I suspect from your code, you would have gotten something like so:

1,
1,2,
1,2,3,
[...]
1,2,3,4,5,6,7,8,9,

The point here is you are using console.log() inside the loop, if you moved it outside the while block, you would get only the last line.

Be careful...

The question has asked to set n=9, and print numbers from 1 to n. So you will need two variables, e.g. i and n. and your while loop might look like:

while(i <= n)

How can we make sure not to have a comma after the last number?

If you note the be careful above, since you know you are starting at var tr = "1" and then adding numbers after that, you could add the comma first when adding new numbers:

tr = tr + ',' + i

Upvotes: 1

William B
William B

Reputation: 1419

It's because JS will convert values into strings when doing string concatenation. tr + n + ',' works when tr is a string.

So if you don't have it as a string already, tr + ',' is undefined,:

var tr;
tr + ','; // String(undefined) + ','

And tr + n is NaN for undefined tr

var tr;
var tr + n; // undefined + [number]

Upvotes: 3

layonez
layonez

Reputation: 1785

Empty string is just output variable here, which we needs because of that condition loop that builds as a single string.

For remove ending comma just check that string on empty:

var n = 1
var tr = ""
while (n <= 9) {
    if(!tr){
        tr += n
    }
    else{
        tr += "," + n
    }
    console.log (tr)
    n++
}

Upvotes: 0

Bubble Hacker
Bubble Hacker

Reputation: 6723

In JavaScript you can append text using the +=. For example:

x = ""
x += "Hello "
x += "World"
console.log(x); //Will print out "Hello World"

And so by declaring an empty string you can then append text to it.

What you are doing in your code is the same idea except you are doing the following:

x = ""
x = x + "Hello "
x = x + "World"
console.log(x); //Will print out "Hello World"

And so you need the string deceleration in the beginning in order to append to it:

x = x + "Hello " //What is x? It is not declared...
x = x + "World"
console.log(x); 

Upvotes: 0

Related Questions