How do I print While Loop? - javascript

Im trying to print the objects in my Array 'ana' but I keep getting a number 2 after the contents are printed. How do I remove the number 2?
var ana = ["I", "Love", "my mother"];
var a = 0;
mother = ana.length;
while(a < mother) {
console.log(ana[a]);
a++;
};
Logs:
I
Love
my mother
2

Don't worry. This is your interpreter behavior. Your code is not actually printing 2. You are seeing 2 because your javascript interpreter prints the value of last assigned value.
In your code, a++; executed in the last loop will return 2(because x++ returns x and then increments it) in the last loop thereby the return value of your whole expression is 2.

You must be printing 2 somewhere else after this loop, your code will only print 'I Love my mother'.. also, there shouldn't be any ; at the end of while loop.
See the demo here

You can move the a++ inside console.log to stop showing it. Like this
console.log(ana[a++]);
The value 2 was getting printed as the return value of your code, which is the last value that a gets.

Related

Javascript prints value in loop though the print is outside the loop

This question was asked before: Trouble understanding what happens during javascript for loop
but the asker didn't get the right answer and so did I. I learn C++ and Python earlier so I get familiar with loop but when I practing this code:
let text = "";
let i;
for(i=0; i<5; i++)
{text += "The number is " + i + " ";}
document.write(text);
the output is totally different to what I expected. I visited W3schools but I can't find the answer
https://www.w3schools.com/js/js_loop_for.asp
https://www.w3schools.com/js/tryit.asp?filename=tryjs_loop_for_om3
I expected the output is "" because text can't be changed but the code prints out: "The number is 0 The number is 1 The number is 2 The number is 3 The number is 4". My question is why the print executes in the loop though the print is outside the loop? Thank you very much!
The print executes as you expect: Only once at the end. In the loop, each time an extra part is appended to text. That is:
[iteration 0] ""
[iteration 1] "The number is 0 "
[iteration 2] "The number is 0 The number is 1"
[iteration 3] "The number is 0 The number is 1 The number is 2"
etc.
Then in the end, you print the final String which is the concatenation of all the partial Strings you 'glued' together.
Saying x += y is the same as saying x = x + y. Standard variables (var and let) are still mutable, so if you initialize it as an empty String, you can still append/replace it later.
Try making text a const instead, and there should be a runtime TypeError because you try to reassign a constant.
why the output not empty string because the text variable not empty anymore after for loop. you have assign string when loop so the text variable not empty anymore

Can anyone tell me that why the {For} Loop in JavaScript is returning all the values including the very first element of the an array?

var arr = [1,2,3,4,5]
for (var i=0; i<arr.length; i++){
console.log(arr[i]);
}
I ran this code on google chrome console and the output was like this:
1
2
3
4
5
In this code I can see that all the elements are been printed but the very first element of the array which is 1 should not print because the value of [i] has already been incremented to 1 and so 2 should be printed instead of 1.
Can someone tell me why is this happening ?
I think you are getting it wrong here. In for loop, we have
for(initialization, condition, change) {
// body
}
So, it workes in this sequence
initialization -> condition -> body -> change
PS: It will go to body if condition evaluates to true

JavaScrpit crashes when incrementing by 2 in a for loop

before you call me out for using wrong terms or sth, I am a newbie programmer.
So, this would be the correct form of the code I'm experimenting with:
for (var i = 0; i <= 10; i += 2) {
nums.push(i);
}
console.log(nums)
However, I don't get why I need to put the = sign after the +. I tried to research this but I couldn't find anything. When I removed the =, JS (Scrimba) crashed. Can anyone explain this to me please?
The third expression in the for loop is to indicate how the i variable increases. This expression is run after every loop iteration.
The second i<=10 is the condition that has to be true for the loop to continue.
Now in your loop starts with i=0, then i=2 is run after 1st iteration. And after every iteration i=2. So i<=10 is true, which is the condition. So this is an infinite loop, leading to the crash.
i+=2 is shorthand for i = i +2, so i is increasing everytime and at some point will exceed 10.
This assumes you have defined nums at top like:
var nums = []. Otherwise you get a different error.
i += 2 mean i = i + 2. In this context, for(A;B; C),C part will run every time in every loop. If you only use "+", the i value will never changed, and loop will be non-stop considering your judgement to stop the loop i < 10 equal to 0 < 10, which is true forever.
Let's take a look at for loop before go to your problem:
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
If you want to end the loop, statement 2 should return a false value.
In your case:
statement 1 is i=1 -> Assign 1 to i variable.
statement 2 is i<=10 -> Execute the code inside brackets if and only if i is less than or equal to 10
statement 3 is i+=2 -> in crease i by 2 after every run.
the point is if you change statement 3 to i+2, it is not an assignment statement anymore, but an operator. So the value of i won't be changed after statement 3 execution.
=> The value of i will always be 1
=> the statement 2 always returns true
=> infinite loop
So your code crashes because of an infinite loop
i += 2 means your are incrementing the value of i by 2.
So, in your case, the loop will start from 0, and it will push in your array. It will keep increasing your i value by 2 and pushing them in the array till it (i) becomes more than 10

extra output after loop

I am learning JavaScript on Codecademy. I am finding so many outputs like below when I use while loop.
for (var i=0; i<5; i++){
console.log("Dhanu identify problems and solve them");
}
var loop = 0;
while(loop<5){
console.log("Do some more");
loop++;
}
I am getting an unwanted output in the last line as 4.
The output you get is simply console.log which logs the last known value of the 'loop' variable: (here in firefox):
It's absolutely not related to your code and you don't have to worry about that.
As stated in another answer, debug console use to log the result of the last line (probably because they are meant to debug).
For example the statement "i = 1" evaluates to "1":
while the statement "var i = 1;" evaluates to "undefined", hence logging "undefined"
you can observe the same behavior by invoking eval on those statements:
You're seeing that because the last statement in your while loop is loop++, which "returns" the current value of loop. This is just a side effect of running code in a console like this. Consoles are basically read-execute-print-loops (REPL), and so they need something to print. If you ran this as a script in a webpage you would not see 4
when you write any statement in developer console then last returned value will be printed...
for example
var a;
it prints undefined on console.
a = 10;
it prints 10 on console.
a = 10; a = a + 5;
it prints 15 on console.
simply when we assign any values or increment or decrement numbers then it returns value after performing that operation...
so, in the above or below code
var loop = 0;
while(loop<5){
console.log("Do some more");
loop++;
}
finally loop++ is 4.

JavaScript Incrementing a number in an array

I want to increment a value in a array when a link is pressed in JavaScript
i Used the following code
<script type="text/javascript">
var i=0;
var numbers = new Array();
function go(val){
numbers[i]=val;
i++;
alert(numbers[i]);
}
</script>
Called the Function like this
<a href='javascript:go(1)' </a>
but always the alert prompts me 'undefined'
The alert is correct -- before you do your alert, you incremented i. You're looking at the next element after the one you just entered.
After calling the method once, your array looks like this:
numbers[0] = 1;
numbers[1] = undefined;
and i == 1.
After calling it again, the array looks like:
numbers[0] = 1;
numbers[1] = 1;
numbers[2] = undefined;
and i == 2.
Hopefully you can see that this method will always alert undefined
That's because you increment "i"
i++;
right before you put up the alert! Thus "i" will alwuays refer to the next array slot to use, not the one you just populated.
You could change the alert to use "i-1"
alert(numbers[i - 1]);
You are setting numbers[0] = 1 and then incrementing i which becomes 1 so alert(numbers[1]) is undefined, because it is undefined.
Do the alert before you increment. Also, use onclick or even better unobtrusively attach the event handlers in JS, not in the HTML.
Yes, it does that because you:
Create a completely empty array, and a pointer at 0.
When the function is called, you set the current pointer value to whatever was passed in...
...and then increment the pointer, so it's now pointing past the end of all the elements.
Now you look at the element in the array that's being pointed at, which has to be undefined because of the way you're managing the i pointer.
What were you hoping for this to do, by the way?
The question doesn't even match the code... or the code doesn't match the question?
"I want to increment a value in a array"
Your code is not incrementing the value, it's incrementing the index!
function go(val){
numbers[i]=val;
i++;
}
(where i is the index of the next undefined array element) is just the same as
numbers.push(val);
and if you need i to equal what will be the index of the next undefined array element then
i = numbers.length;
To increment the value you would have to first have numeric values for some array elements; then your function would need the index of which value to increment
var numbers = [0,0,0,0];
function go(i){
numbers[i]++;
}
// testing
go(1);
go(3);
go(1);
alert(numbers);
will show 0,2,0,1
But if your entire goal is to put a value into a new element on the end of an array then just use .push()
and .length will tell you how many elements there are; there is no need to increment an i

Categories

Resources