Javascript for loop? - javascript

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 + ': ';

Related

Problem with Javascript localStorage for-loop

I am using localStorage to store incoming message: {"lastTid":22,"Hour":10,"min":31,"Second":34} where the time is increasing in every new incoming object, e.g. next object: {"lastTid":22,"Hour":10,"min":31,"Second":35}.
The new messages are being stored in localStorage correctly as seen here:
My Javascript code implements the localStorage.getItem and .setItem correctly to retrieve and get my incoming data message, which will be rendered with .innerHTML to var hst, which hst = document.getElementById("highscores"). all code below
The ElementId "highscores" is assigned to <table> tag in my html and comes out as seen here:
#js code snippet#
var hst = document.getElementById("highscores");
function onMessageArrived(message) {
var data = JSON.parse(message.payloadString);
var highScores = [data];
var array = JSON.parse(localStorage.getItem('highscores') || '[]');
array.push(highScores);
localStorage.setItem('highscores', JSON.stringify(array));
for (var i = 0; i < array.length; i++) {
hst.innerHTML += "<tr><td>" + array[i][0].Hour + ":"+ array[i][0].min + ":" + array[i][0].Second + "</td><td>" + array[i][0].lastTid + "</td></tr>";
}
};
My problem is, because of my For loop, when a new message arrives, my loop goes through and renders the previous message and the new message, while the old message is still in the table(please see the table image above). It is displaying object 0, object 0 & 1, then object 0, 1 & 2 all in the same table. Instead of 0, then 1 after, then 2 ... n.
I wish to display the values in proper order and also keep those values even after the page is reloaded. Desired result:
Don't append directly hst.innerHTML +=...
try something like this
let html = ''
for (var i = 0; i < array.length; i++) {
html += "<tr><td>" + array[i][0].Hour + ":"+ array[i][0].min + ":" + array[i][0].Second + "</td><td>" + array[i][0].lastTid + "</td></tr>";
}
hst.innerHTML = html
I think the problem is your always appending the array content at hst.innerHTML each incoming message, so the previous loop content remains. It's also not recommended for performance to manipulate DOM inside loops.
let res = '';
for (var i = 0, l = array.length; i < l; i++) {
res += '<tr><td>' + array[i][0].Hour + ':' + array[i][0].min + ':' + array[i][0].Second + '</td><td>' + array[i][0].lastTid + '</td></tr>';
}
hst.innerHTML = res; // You overwrite the content instead of appending each time.

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

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.

Returning a String instead of looping print statement

I'm new to Javascript and I'm curious as to how to store values in a string and then return it. In the example below 2 numbers are picked, for example 2 and 8, and the program should return 2x1 =2, 2x2=4,..... all the way up to 2x8 =16. This can obviously be done by constantly looping a print statement as I have done, but how would I be able to store all the values in a String and then return the string.
function showMultiples (num, numMultiples)
{
for (i = 1; i < numMultiples; i++)
{
var result = num*i;
console.log(num + " x " + i + " = " + result+ "\n");
}
}
console.log('showMultiples(2,8) returns: ' + showMultiples(2,8));
console.log('showMultiples(3,2) returns: ' + showMultiples(3,2));
console.log('showMultiples(5,4) returns: ' + showMultiples(5,4));
function showMultiples(num, numMultiples) {
// the accumulator (should be initialized to empty string)
var str = "";
for (i = 1; i < numMultiples; i++) {
var result = num * i;
// use += to append to str instead of overriding it
str += num + " x " + i + " = " + result + "\n";
}
// return the result str
return str;
}
var mulOf5 = showMultiples(5, 10);
console.log("multiples of 5 are:\n" + mulOf5);
The operator += add the a value (right operand) to the previous value of the left operand and stores the result in the later. So these two lines are the same:
str = str + someValue;
str += someValue;
You could just use string concatenation:
var finalResult = ""
...in your loop...
finalResult += num + " x " + i + " = " + result+ "\n"
Often you can also just collect the results in an array and use join to append them.
var lines = [];
... in your loop:
lines.push(num + " x " + i + " = " + result);
... afterwards
console.log(lines.join("\n"));
In case you wanted to use ES6 syntax using backticks for a template string, you can use the below. This is a little more readable and is exactly where it is useful (so long as you can use ES6 wherever you're using JavaScript).
function showMultiples(num, numMultiples){
let result = '';
for(let i = 1; i < numMultiples; i++){
result += `${num} x ${i} = ${i * num}\n`;
};
return result;
}
console.log(showMultiples(2,8));

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>";
}

How to create an array of variables from an array in Javascript

I have a variable called "information" which creates a multi-dimensional array. For each row in the array, I want to return a variable whose name is the first value in the array. In other words, given the 'information' array below, I'd want the following output:
var lunalovegood = information[i][2] + ' ' + information[i][3] + ' is a ' + information[i] [1] + '!'; //Luna Lovegood is a Ravenclaw!;
var dracomalfoy = information[i][2] + ' ' + information[i][3] + ' is a ' + information[i] [1] + '!'; //Draco Malfoy is a Slythering!;;
var hermionegranger = information[i][2] + ' ' + information[i][3] + ' is a ' + information[i] [1] + '!'; //Hermione Granger is a Gryffindor!;;
In other words, I want to be able to work with each of the elements in the 'information' array to create some markup. I already know how to get the information I need given the information array, but as you can see below I'd have to declare separate variables for each of the names.
for (var i = 0; i < information.length; i++) {
var htmlString = information[i][2] + ' ' + information[i][3] + ' is a ' + information[i] [1] + '!'; //Luna Lovegood is a Ravenclaw!
$('div').html(htmlString);
} //end for loop
var information = [
['lunalovegood', 'Ravenclaw', 'Luna', 'Lovegood', '(chaser)', 'lovegood.jpg', 4]
['dracomalfoy', 'Slytherin', 'Draco', 'Malfoy', '(seeker)', 'malfoy.jpg', 2],
['hermionegranger', 'Gryffindor', 'Hermione', 'Granger', '(none)', 'granger.jpg', 3],
];
The javascript below creates three variables called 'lunalovegood', 'dracomalfoy', and 'hermionegrange', but it's the long way of creating variables. How do I create these variables, one for each row in the array, by looping through the 0th indexed element in the 'information' array?
var myVariables = {}
,varNames = ["lunalovegood","dracomalfoy","hermionegranger"];
for (var i=0;i<varNames.length;i+=1){
myVariables[varNames[i]] = 0;
console.log(lunalovegood);
}
Your current approach just needs a most minor tweak to not require the second array.
var students = {}, i;
for (i = 0; i < information.length; ++i)
students[information[i][0]] = information[i][2] + ' ' + information[i][3] + ' is a ' + information[i][1] + '!';
Now the key is set by taking the first item of the Array. You would then do the following for your text,
students['lunalovegood']; // "Luna Lovegood is a Ravenclaw!"
You're also missing a , in your information literal.
This should help you:
Every variable in the global scope can be accessed as a string property of the window object
var myvariable = 4;
alert(window["myvariable"]); // will alert 4
window["newvariable"] = 6;
alert(newvariable); // will alert 6
I agree with Bergi. Variables should represent a fixed finite set of members defined by code; data (as in the contents of a list) should generally not introduce new variables.
As such, here is the approach I would recommend (note that I've added a bit more than the "minimum required"; good luck!):
// Using a function makes it easy to change details and avoid leaking
// variables accidentally.
function loadWizards(information) {
var wizards = [];
for (var i = 0; i < information.length; i++) {
var info = information[i];
var name = info[0];
// Mapping to named properties means we can forget about indices!
wizards[name] = { // <- use Name to map to our Wizard object
house: info[1],
// ..
image: info[7]
};
}
return wizards;
}
// I have no idea if they are wizards, but give variables useful names.
// 'information' is too generic.
var wizards = loadWizards(information);
// Then later on, use it as:
alert("Hello " + wizards['hermionegranger'].name + "!")
// ^-- property access by Name
var formattedInfo = {};
$.each(information, function (i, v) {
formattedInfo[v[0]] = v[2] + ' ' + v[3] + ' is a ' + v[1];
});
there is a missing comma at the end of the 1st line of your definition of information.
BTW, I like Harry Potter very much.

Categories

Resources