How does Javascript variable works? - javascript

Recently started learning Javascript.
Given an assignment for my class, to click a button (a number 10 is written on the button), and there has to be "Result = 55". (here all numbers from 0 to 10 are added)
To change words by clicking buttons, wrote code like this:
function myFunction(num) {
var p = document.getElementById("mydata");
for (var i = 0; i <= num; i++) {
sum = sum + i;
p.innerHTML = "Result = " + sum;
}
}
After submitting assignment for school, learned that had to add var sum = 0 above var p = document.getElementById("mydata")
However, do not understand what var sum = 0 means. As for looks already show when to begin and end calculating, feel like it doesn't have to be there.

var sum = 0; declares a local variable named sum, and sets its initial value to 0.
If you don't do this, when you do:
sum = sum + i;
the variable sum is initially undefined, and adding i to it results in NaN (Not a Number).
Some languages (e.g. PHP) automatically treat initialized variables as 0 in arithmetic expressions, but JavaScript doesn't do this, so you need to specify the initial value of the variable.
This has nothing to do with the way the for loop determines when to begin and end. It's about how to correctly add the numbers along the way.
It doesn't have to be before the p assignment, but it needs to be before the for loop.
Also, the line
p.innerHTML = "Result = " + sum;
doesn't need to be inside the loop. You should wait until the loop is done.

Related

Having trouble with a Javascript adding system (simple but I'm slow)

So I am trying to make a program here where I press a button and once its pressed I input a number (from 1-3) and then it outputs the inputted value.
Then you can press the button again and add another value (again from 1-3) and it adds the second input to the first input and so on.
This is the code I've got so far and it doesn't work, it just outputs my inputted value and that's it. Nothing gets added and updated.
<script type="text/javascript">
function addone()
{
x=parseInt(prompt("What goal importance did you complete?"));
var sum = 0;
if (x === 1)
{
sum = sum + x;
}
else if (x=== 2)
{
sum = sum + x;
}
else if (x=== 3)
{
sum = sum + x;
}
document.getElementById("myBtn").innerHTML = x;
}
</script>
The button and the ouput are with:
<button onclick="addone()">Coins</button>
<h1>Coins:</h1>
<h4 id='myBtn'>0</h4>
As pointed out by #Aplet123, each time you execute the addOne function, you restart the sum as 0.
The simplest way is to initialize it outside the function.
By the way, there is no need for the elseif conditions in your code, regarding the feature you want to achieve, the best, for readability should be to use a AND condition :
<script type="text/javascript">
var sum = 0;
function addone()
{
x=parseInt(prompt("What goal importance did you complete?"));
if (x >= 1 && x <=3)
{
sum = sum + x;
}
document.getElementById("myBtn").innerHTML = sum;
}
</script>
You have to fix one thing before moving on. You are instantiating the sum as 0 whenever you run the function. To fix this, declare the sum outside of the function. You can reset it if you want later in the program if you like.
Next, you want to accept only 1, 2 or 3 as the input. You can shorten the if else condition so that it checks that input is more than or equal to 1, but less than or equal to 3.
Finally - You are adding the values of input to the sum variable. The variable x is not changing itself. So, you will always see the number you input. Change the innerhtml value to sum.
EDIT - I have also included comments in the code below -
var sum = 0; //Declare sum outside the function
function addone(){
let x=parseInt(prompt("What goal importance did you complete?"));
if (x >= 1 && x <=3){ //Shorten the if else condition
sum += x;
}
document.getElementById("myBtn").innerHTML = sum; //Display the sum
}

Is it Possiable to call to previous increments of a variable?

for example lets say i have a loop that is doing basic counting, while the variable is less than 16 the loop will run and at the end of the loop you add 2 to the variable and add one to a "count" variable
what i want to know is if its possible to callback to any of the previous variables for either variable for example can i count all the times count % 2 === 0?
im not quite sure if once a variable makes any kind of change if all previous versions of that variable are gone
http://codepen.io/anon/pen/Gojoxm
var two = 0;
var count = 0;
while ( two < 16) {
two += 2;
count++;
};
console.log(count);
If I understand you right, then no, you cannot. When you assign a new value to a variable, the previous value is lost.
You have to either run this loop again or store intermediate values in an array:
var values = [];
var two = 0;
while (two < 16) {
two += 2;
values.push(two);
}
console.log(values.length); // the same result
Then, you will always be able to do whatever you want with these values.
For example, you can check if there were any odd values:
var anyOddNumbers = values.some(function(x) { return x % 2 === 1; }); // false

Javascript: Arrays and For Loop Basics

I'm new to javascript and have been trying to teach myself the basics. I do have some experience with C++.
I came across this example in the source I'm using for studying and the for loop looks strange to me:
<html>
<head>
<script type="text/javascript">
<!--
function ReadCookie()
{
var allcookies = document.cookie;
alert("All Cookies : " + allcookies );
// Get all the cookies pairs in an array
cookiearray = allcookies.split(';');
// Now take key value pair out of this array
for(var i=0; i<cookiearray.length; i++){
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
alert("Key is : " + name + " and Value is : " + value);
}
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
<input type="button" value="Get Cookie" onclick="ReadCookie()"/>
</form>
</body>
</html>
Would someone mind explaining why there is a [0] and [1] near the end of these statements?
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
A clearer way to write this statement is this:
var parts = cookiearray[i].split('='),
name = parts[0],
value = parts[1];
That doesn't have anything to do with the for-loop itself. Split returns an array of tokens; the string is split up at the given delimiter. You're simply accessing the first and second tokens in this array.
String.split creates an array using the assigned delimiter (in this case '='). The [0] and [1] are selecting the first and second elements of the array respectively (Javascript array element indexes start at zero).
Those are used to access the items in the arrays that you create.
It's more clear what they do, and also better for performance, if you put the array in a variable and access that. That way you don't have to create two identical arrays:
var cookie = cookiearray[i].split('=');
var name = cookie[0];
var value = cookie[1];
The code is splitting each cookie pair key=value into key ([0]) and value ([1]).
A for loop is an iterator. You can sort of think of it like a counter, or stepping progression. If you want to do something x number of times, then a for loop is your best friend. The issue, when you are first learning, is figuring out how to use them effectively.
I'll give you a relevant and nonrelevant (simplified) example:
Nonrelevant:
// Increase the value of x and print the new value to the console 20 times.
var x = 6;
for(var i = 0; i < 20; i++) {
x++;
console.log("Value of x: " + x);
}
If you take a close look it's really rather logical. You define an iteration variable i, tell it when to stop (i < 20...so stop if i = 20), how to progress with each iteration (i++ or i + 1).
So the code will enter the loop when i = 0...it will add 1 to the value of x (x++), resulting in x = 7. It does the same for each iteration, so when i = 1, x (7) + 1 = 8, so on and so forth until i = 20, then the code breaks out of the loop and continues on it's merry little way. When it breaks we have just added 1 to x 20 times. Since x used to equal 6, it now equals 26.
Relevant:
// Given array of length 10, print each element to the console
for (var i = 0; i < cookiearray.length; i++){
console.log(cookiearray[i]);
}
So here the for loop is the same, it simply iterates until i equals the length (number of elements, in this case) of the array (so 10 times). When i = 0, our code prints the element of the array at cookiearray[0]...when i = 1 it prints cookiearray[1]...so on and so forth for the entirety of the array.
What may confuse you in the example is the split function. Split returns an array. So this line:
name = cookiearray[i].split('=')[0];
...actually means assign the first element of the new array created from splitting the cookiearray's element at position i.
Let's assume that cookiearray[0] = "Hello=World". When i = 0, our code splits the string "Hello=World" into a new array where the element at the 0 position is "Hello", it then assigns this to the local variable name. So name = "Hello".

Taking values from one array and to obtain a different value from a separate array. JavaScript

I'm not entirely sure how to word what I am asking here but I have an assignment where two arrays are present. One array contains strings which are the makes of cars. The second array contains the price of that car. The program is to run a for loop through the first array, identify the values that contain that specific make, and then add the prices up in the second array.
This is what I have:
<html>
<script>
make = new Array();
make[0]='honda';
make[1]='toyota';
make[2]='pontiac';
make[3]='honda';
price = new Array();
price[0]=35000;
price[1]=35000;
price[2]=40000;
price[3]=45000;
function totalByColor(parameter1){
total=0;
for(i=0;i<make.length;i++){
if(make[i]=='honda'){
for(b=0;b<price.length;b++){
make[i]=price[b]; //This is where I need help!
total = total + price[b];
};
} else {
};
return total;
};
return total;
};
</script>
<input type='button' value='test' onclick="alert('Return = '+totalByColor('honda'))">
</html>
So I need to set the program up to identify the value in make[0] is relevant to price[0] and make[3] is relevant to price[3], so price[0] and price[3] can be added together in the second for loop, any one have any idea? Thanks in advance for any help or guidance on this issue
If the indices are the same, you don't need another for loop; just use your var i:
var total = 0;
for (var i = 0, len = make.length; i < len; i++) {
if (make[i] === 'honda') {
total += price[i];
}
}
return total;
total should be a local variable, and is defined as 0 first, then you can use += to redefine total as total + price[i]. It's shorthand for total = total + price[i]. I also included var before the i in the for loop, because it should be local, and not global; and, you don't need so many semi-colons: after brackets for example } (so long as it's not an object you are defining). One more thing is that you have a return statement in your for loop, which means it will only loop over one value before ending the function. The return statement should be after the for loop.

A basic Javascript For loop

# http://jsfiddle.net/defencedog/rrKYW/
A recent observation has deeply embezzled my knowledge of js. Look at the code below:
var x = "";
function postbody() {
for (i = 0; i < 5; i++) {
x = x + "<sup>" + i + "</sup><br/>";
document.getElementById("posti").innerHTML = x;
}
}​
The above code's output is similar to that of the following & that is the thing vague to me
var x = "";
function postbody() {
for (i = 0; i < 5; i++) {
x = x + "<sup>" + i + "</sup><br/>";
}
document.getElementById("posti").innerHTML = x;
}​
the latter code must giv me a single (to be concise last value of x) output & not the whole iterated output?
Both snippets accomplish the same thing; The first snippet is just less performant as it overwrites the value 5 times as the string is built up instead of writing the final string once.
unrelated: i is an implicit global. use var.
both will cause a same result.
x = x + ...
Sure it does. You add new code to x in each iteration and then set it in the element. setting innerHTML overwrites the entire content of the element.
In the first loop, each iteration will overwrite the html of the element with a little larger html, but the final iteration is the one that overwrites it with the 'complete' value of x.
So the end results are the same, but the first one is quite a bit slower.
The two examples are identical because on the first the innerHTML is being overwritten on each iteration while the value of the variable x is being concatenated with the other strings. By the last iteration, the element's innerHTML will have x's total value.

Categories