Unclear behavior of While loop [duplicate] - javascript

This question already has answers here:
Javascript while loop return value
(3 answers)
Closed 2 years ago.
As someone new to js, I was playing with loops when I encountered some peculiar behavior with the following code:
var i = 5;
while(i!=0){
console.log(i);
i--;
}
OUTPUT: 543211
I replicated the same code in c++ :
int i = 5;
while(i!=0){
cout<<i;
i--;
}
OUTPUT: 54321
It'd help to know if I'm missing some important differences between the two languages.

If you run the code in the browser console, whatever the last statement evaluates to will log to the console as well. It's not actually getting console.log'd, though.
For example, if you do this:
var i = 5;
while(i!=0){
console.log(i);
i--;
'';
}
At the end of your list you will see ''

Related

Why this Insertion Sort method won't work if I change one VAR for LET in nested loops? [duplicate]

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
What is the difference between "let" and "var"?
(39 answers)
Closed 4 months ago.
I'm currently doing a Javascript bootcamp. Today we were studying Sorting methods. The teacher provided us with "template" not-built-in functions. Another teacher also said that nowadays there's no reason to use VAR anymore to define a variable, that we should always use LET (and const, etc.).
So I copypasted his code in VSCode tu run it and study it. Then I decided to change all the VARs for LETs, and the code stopped working. I tried one by one and discovered it is one in particular (inside a loop that is nested in another loop) that if changed, then the code throws an error. So i would like to understand why is this happening? We've used lots of nested loops and this is the first time it happens.
Here is the code:
// INSERTION SORT
function insertionSort(arr){
let currentVal;
for(let i = 1; i < arr.length; i++){
currentVal = arr[i];
for(**var** j = i - 1; j >= 0 && arr[j] > currentVal; j--) {
arr[j+1] = arr[j]
}
arr[j+1] = currentVal;
}
return arr;
}
let hola = insertionSort([26,54,2,1,9,20,99,76,4]);
console.log(hola);
I wonder if this is related to the scope... If I delete this VAR, the code runs with no issue.... what's going on

Javascript: Uncaught type error: cannot read property innerHTML of undefined [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 1 year ago.
I cannot solve this error , it tells me that my buttons are undefined and cannot read their innerHtml attribute, the convert method is defined in the original code file and i have no problem with it,can you help me , the error comes from the code section below:
var btnsArr = document.getElementsByClassName("btn")
for (var i = 0; i < btnsArr.length; i++) {
btnsArr[i].addEventListener("click", function () {
Convert(btnsArr[i].innerHTML);
return false;
})
} ```
This is an issue of scoping in javascript aka closure inside loop problem. When getting to the function execution at runtime, i has completed its loop and is out of bound for the array.
You need to bound the variable:
for (var i = 0; i < btnsArr.length; i++) {
(function(x) {
btnsArr[x].addEventListener("click", function () {
Convert(btnsArr[x].innerHTML);
return false;
});
})(i)
}
I can see a very common issue in the code, is that your array of elements (btnsArr) is used to define the maximum index for your for. The issue here is that btnsArr.length must be btnsArr.length - 1 instead.
why?
if btnsArr has 3 elements it's range will be from 0 to 2, but your for is expecting from 0 to 3 (because btnsArr.length is 3). Then, probably it is failing in the last array element btnsArr[3] that does not exist.
I hope that it helps at least to cover some exception.

Understanding asynchronous callbacks [duplicate]

This question already has answers here:
setTimeout in for-loop does not print consecutive values [duplicate]
(10 answers)
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 8 years ago.
I'm new to asynchronous programming, and I'm having a hard time getting the concept.
Please help!!!
Ive come up with a simple example:
for (var i = 1; i <= 10; i++) {
setTimeout(function () {
console.log(i);
}, 1000);
}
All I want is to print the indexes in ascending order but due to asynchronous action forced by the setTimeout i'm getting the last index printed out 10 times.
I understand why this happens...
No matter what I've tried (I don't think my misunderstanding needs elaboration) I failed solving this stupid riddle...
Im obviously missing something basic.
Please help me figure it out.
It's because all those functions use the same variable i, which is equal to 10 during invocation of them. Try something like this:
for (var i = 1; i <= 10; i++) {
setTimeout((function (k) {
return function(){
console.log(k);
}
}(i)), 1000);
}
It's because JavaScript has closures. You can read about them here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures

A weird while loop syntax [duplicate]

This question already has answers here:
Please help me understand the "while" loop in this JavaScript snippet
(3 answers)
Closed 8 years ago.
this code: http://ajaxian.com/archives/attack-of-the-ie-conditional-comment
var ie = (function(){
var undef, v = 3, div = document.createElement('div');
while (
div.innerHTML = '<!--[if gt IE '+(++v)+']><i></i>< ![endif]-->',
div.getElementsByTagName('i')[0]
);
return v > 4 ? v : undef;
}());
Could you please explain to me why this while loop works? Is that even correct syntax?
Edit: I do understand what this code is trying to do, but the syntax is just not obvious to me..
It works because the first statement gets executed and due to comma operator, only the second statement is considered for evaluation, which will evaluate to true or false.
This while loop is correct, because in while statements are seperated by , so the last statement's value will be used as condition of while.
This while loop will finish whenever div.getElementsByTagName('i')[0] will be null or undefined.

Javascript if in x [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Test for value in Javascript Array
Best way to find an item in a JavaScript Array ?
Javascript - array.contains(obj)
I usually program in python but have recently started to learn JavaScript.
In python this is a perfectly valid if statement:
list = [1,2,3,4]
x = 3
if x in list:
print "It's in the list!"
else:
print "It's not in the list!"
but I have had poblems doing the same thing in Javascript.
How do you check if x is in list y in JavaScript?
Use indexOf which was introduced in JS 1.6. You will need to use the code listed under "Compatibility" on that page to add support for browsers which don't implement that version of JS.
JavaScript does have an in operator, but it tests for keys and not values.
p.s. original answer is from 2011, now it's supported by all browsers in use. https://caniuse.com/?search=indexof
In javascript you can use
if(list.indexOf(x) >= 0)
p.s. only ancient browsers don't support it
https://caniuse.com/?search=indexof
in more genric way you can do like this-
//create a custopm function which will check value is in list or not
Array.prototype.inArray = function (value)
// Returns true if the passed value is found in the
// array. Returns false if it is not.
{
var i;
for (i=0; i < this.length; i++) {
// Matches identical (===), not just similar (==).
if (this[i] === value) {
return true;
}
}
return false;
};
then call this function in this way-
if (myList.inArray('search term')) {
document.write("It's in the list!")
}

Categories