why do i have to declare javascript variable with an empty value? - javascript

why must i declare the var msg = ' '; and not just var msg; and also why msg += 'Round ' + roundNumber + ':';' and not just msg = 'Round ' + roundNumber + ':';.... why should i add + sign before equals ?
var score = [24, 32, 17];
var arrayLength = score.length;
var roundNumber = 0;
var i;
var msg = '';
for (i = 0; i < arrayLength; i++) {
roundNumber = (i + 1);
msg += 'Round ' + roundNumber + ':';
msg += score[i] + '</br>'
}
document.getElementById('answer').innerHTML = msg;
output of the above code:
Test 1:24
Test 2:32
Test 3:17
output of the code when msg is declared only rather than giving an empty value and assigning msg without the plus (+) sign:
Test 3:17

You have confused a number of Javascript concepts.
Firstly, Javascript variables must be declared but do not have to be initialised. To declare a Javascript variable, you use the var keyword. For example, var msg; is valid Javascript code. As well as declaring a variable, you can optionally initialise it using an = sign. So, for example, var msg = ''; declares the msg variable and initialises it to an empty string. Importantly for you, if you do not initialise a Javascript variable, it is set to a special type of variable called undefined.
The second Javascript concept you have confused is assignment and calculation. In Javascript, you use the = sign to assign a value to a variable. So, for example x = 1; sets the value of the x variable to 1. The += operator is a shorthand operator. So, x += y; is exactly the same as x = x + y;. The crucial difference is that the = operator overwrites the existing value of the variable, whereas += uses the existing value to calculate a new value.
So, in the specific case of your code, you have used the += operator on the msg variable. As explained, the += operator performs a calculation on the existing value of the variable. So, this is why you had to initialise your variable when you declared it - otherwise you would have been performing a += on an undefined variable - which, in your case, does not perform the string concatenation that you expected.
The specific instances on when you should use what very much depends upon what the goal of your code is.

Related

Javascript - Display array elements

I am trying to run a simple Javascript to display the elements of an array that I create by splitting a string. The code is as follows:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Loops</h1>
<p id="demo"></p>
<script>
var text = "01/01/2016";
var parts = text.split("/");
var i;
for (i = 0; i < parts.length; i++) {
var x += parts[i] + "<br>";
}
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
The above code does not display anything on the browser and I can't for the life of me figure out where the error is. Can someone advise?
This line is tricky, so any JavaScript compiler would complaint:
var x += parts[i] + "<br>";
Uncaught SyntaxError: Unexpected token +=
You can't declare a variable with the "+=" assignment operator.
Let's rewrite this assignment:
var x = x + parts[i] + "<br>";
When it works, the result is the same. Only that the first time this runs, x is undefined, not initialized yet. Concatenating undefined to any a string will contain the string undefined in the result.
But does it re-declare the variable? No, because a concept called hoisting, any variable declaration, even inside a loop, is pushed to the top of the scope, in this case the global scope. (We're not talking about let and const)
To solve that, before you read from this variable, you need to definitely assign to it, i.e. initialize.
var x = '';
Later you'll be able to use the operator +=, and then you don't need to use the var keyword.
fgil give you good answer - you declare x variable in loop, at the first - it's not initialized (you have get error on += ), and second - you reset variable each iteration by declaring it at the loop. But I think that this loop is not needed. You can make code more simple and short if you will use method join of Array. Look at this:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Loops</h1>
<p id="demo"></p>
<script>
var text = "01/01/2016";
var parts = text.split("/");
var x = parts.join("<br>") + "<br>";
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
Here fiddler with sample
You can do it in one line:
document.getElementById("demo").innerHTML = "01/01/2016".split("/").join("<br>") + "<br>";
you are just failing in a basic concept. var x must be declared before the loop, like this:
var x = '';
for (i = 0; i < parts.length; i++) {
x += parts[i] + "<br>";
}
Define x outside the for loop.
var text = "01/01/2016";
var parts = text.split("/");
var x = "";
for (i = 0; i < parts.length; i++) {
x = x + parts[i] + "<br>";
}
document.getElementById("demo").innerHTML = x;

Why does a variable in += operation with concatenation yield mixed results based on how it's defined?

When I declare the variable and in the next statement assign values via plus equals (+=) operator by concatenating other variables and text, I receive all data stored in my object. However, it is preceded by 'undefined'. In an effort to remove the initial undefined status of the variable, I have defined it ahead of the concatenation, however, this then breaks my plus equals operator, truncating the results.
for (var j = 0; j < itemResponses.length; j++) {
var itemResponse = itemResponses[j];
var responseTitle = itemResponse.getItem().getTitle();
var responseAnswer = itemResponse.getResponse();
var responseComplete; // Inserts undefined at start of log
// var responseComplete = ""; // Breaks += operation
// var responseComplete = new String(); // Breaks += operation
responseComplete += (responseTitle + ": " + responseAnswer + "; ");
}
Logger.log(stringData);
Log for var responseComplete;
[16-09-15 15:38:02:256 PDT] undefinedName: Name; Member Number: 0000; Date: 2016-09-09 09:00; Duration: 00:00:09;
// **** Inserts 'undefined' at head of log
Log for var responseComplete = new String();
[16-09-15 15:39:02:610 PDT] Duration: 00:00:09;
// **** Breaks += operator.
Log for var responseComplete = "";
[16-09-15 15:39:42:010 PDT] Duration: 00:00:09;
// **** Breaks the += operator.
Insight into my misunderstanding of the language is greatly appreciated.
(this project is written and executed in Google Apps Script Editor)
The last two scenarios are easy to explain: You are resetting responseComplete to an empty string in each loop, so += doesn't make a lot of sense since you're always concatenating to an empty string.
responseComplete += abc
is the same as saying
responseComplete = responseComplete + abc
and since responseComplete = "" in every loop, then
responseComplete = "" + abc = abc
The first scenario is little more tricky. Since var is evaluated at parse time and not run time, this is the same as declaring the variable outside the for loop, and since it is declared but not assigned to any value, the first time it is equal to undefined
responseComplete = responseComplete + ABC
responseComplete = undefinedABC
The second loop and onward the value if responseComplete is retained.
responseComplete = responseComplete + _nextValue
responseComplete = undefinedABC + _nextValue = undefinedABC_nextValue

First element in object is undefined using += operator

I have a problem to use the operator += in an object.
Because i have to change the variable dynamically i use an object as variable.
But if i use the += operator the first element in the output always gets undefined. I think thats because the object is initialized empty.
What is the best solution to prevent to output that element ?
Here goes my example code:
var dynamicVariable = {};
var group = "apples";
for(var i = 1; i<5; i++)
{
dynamicVariable[group] += " Apple" + i + "<br>";
}
document.getElementById("fruits").innerHTML = dynamicVariable[group];
jsFiddle
This is happening because dynamicVariable[group] has the value undefined before you start appending to it. undefined + " Apple1" is "undefined Apple1".
You need to initialize it to an empty string first:
dynamicVariable[group] = "";
for(var i = 1; i<5; i++) {
dynamicVariable[group] += " Apple" + i + "<br>";
}

Javascript for loop?

I'm currently studying javascript on my own and would like to see if anyone could help me clarify this questions I have. I'm currently learning loops and came across this code in the book:
var scores = [34, 45, 66, 1023, 1030, 'Done!'];
var arrayLength = scores.length;
var roundNumber = 0;
var msg = '';
var i;
for (i = 0; i < arrayLength; i++) {
roundNumber = (i + 1);
msg += 'Round ' + roundNumber + ': ';
msg += scores[i] + '<br />';
}
document.getElementById('answer').innerHTML = msg;
<div id="answer"></div>
Now that loops through the array and returns all numbers in the array. But If i were to change:
var msg = ''; to var msg;
msg = 'Round ' + roundNumber + ': ';
it only returns the last item in the array. Why does that affect it? How does making the msg variable as null change everything?
There are two things here you must understand:
=
It is an assignment operator. The operation var x = 'something' means that any value inside x will be forgotten, and replaced by the new value 'something'.
+=
It is a binary operator. It increments the value of a variable, so x += 'something' will add the value 'something' to whatever value was already inside the x variable. It's the same as x = x + 'something'
So, don't initializing a value for the variable, would just make it not having anything to add to:
var msg;
msg += 'Round' //This would give you 'undefinedRound'
Now, in your case, you removed the + sign, so you used a simple assign operator =. Every time the for loops, it will reset the variable's value.
Making the following declaration
var msg;
DOES make msg == undefined initially, but the problem is that second line you changed:
msg = 'Round ' + roundNumber + ': ';
This causes msg to be equal to ONLY THAT value on the right side of the value assignment. By using += rather than just =, you are continuously concatenating onto previous values of msg.
msg += 'Round ' + roundNumber + ': '; //update the msg by adding previus value plus current value
msg = 'Round ' + roundNumber + ': '; //update the msg by adding only the current value. Just like assigning new value in the msg variable.
The issue is at the following line:
msg = 'Round ' + roundNumber + ': ';
The line should actually read:
msg += 'Round ' + roundNumber + ': ';

Putting together a string in javascript - ReferenceError: invalid assignment left-hand side

What am I doing wrong here?
function F2()
{
for(i = 1; i < 7; i++)
{
('zone'+i+'Data') = ('1'+document.getElementById('Z'+i+'Operate').value +
document.getElementById('Z'+i+'OnTimeH').value +
document.getElementById('Z'+i+'OnTimeM').value +
document.getElementById('Z'+i+'Duration').value +
document.getElementById('Z'+i+'Repeat').value +
document.getElementById('Z'+i+'Extra').value);
('op'+i).innerHTML = ('zone'+i+'Data');
}
}
zone1Data, zone2Data, etc are declared externally. If I don't run the loop and use zone1Data = rather than ('zone'+i+'Data') = it works ok so I think it is something wrong with my syntax for this .... and probably also the last line too.
Any ideas how to do this??
('zone'+i+'Data') =
is an invalid way to assign dynamic variables
use array notation with the variable name to create a new variable
window['zone'+i+'Data'] = "something";
this['zone'+i+'Data'] = "something"
someOtherObject['zone'+i+'Data'] = "something";
you can then use dot notation to access it
console.log( window.zone0Data );
console.log( this.zone0Data );
console.log( someOtherObject.zone0Data );
I would avoid the window one as that would pollute the global namespace
And as Ingo Bürk mentions it would be better to put these into an array
var zoneData = new Array();
for(i = 1; i < 7; i++) {
zoneData[i] = ('1'+document.getElementById('Z'+i+'Operate').value +
document.getElementById('Z'+i+'OnTimeH').value +
document.getElementById('Z'+i+'OnTimeM').value +
document.getElementById('Z'+i+'Duration').value +
document.getElementById('Z'+i+'Repeat').value +
document.getElementById('Z'+i+'Extra').value);
}
and each zone data will be accessible by its index
console.log(zoneData[1]);
console.log(zoneData[2]);

Categories

Resources