For loop and hoisting [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I have a question.
For example I use for loop like this:
for ( var i = 0; i < some_length; i++ ) {
/* some code */
}
After that variable i is hoisted.
Does it mean that I always should declare i variable at the beginning of the scope?
var i;
for ( i = 0; i < some_length; i++ ) {
/* some code */
}
UPD:
I know that both loops work the same way.
I mean which one is more correct?

Modern JavaScript supports block scoping via let.
for ( let i = 0; i < some_length; i++ ) {
/* i is defined here */
}
/* i is not defined here * /
Back to the original quetion: which example is more correct?
I would argue that the second one is less error prone.

In your example - first one is classic type declaration of your iterator variable. In other cases like when you operate on many functions/objects/variables i recommend you to declare all variables on the beginning of your scope/object/function.
When you see code wrote in that way in future it will be much easier to see what is going on in here. You just look on first 10-15 lines of code and you would not search for every variable inside - everything will be explained in the beggining of your code.

Related

How to count backwards [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Hey guys im developing something and I need to fix this please give me some feedback on how to improve this. (how to make it cleaner, easier to read , etc). Here's the code!
function wordFliper(word) {
let wordOutput = "";
let reverseIndex = word.length - 1;
for (let index = reverseIndex; index >= 0; index--) {
let storage = word[index];
wordOutput = wordOutput + storage;
}
return wordOutput;
}
I would remove some variables (variables that are used once in loop and then assigned to a function variable) to reduce code and rename one like this:
/// <summary>Function to flip words backwards</summary>
/// <param name="word" type="string">Word to be flipped</param>
/// <returns type="string">Word flipped</returns>
function wordFlipper(word) {
let flippedWord = "";
for (let i = word.length - 1; i >= 0; i--) {
flippedWord += word[i];
}
return flippedWord;
}
Also IMHO use i variable instead of index (for loop incrementer)
And Also get used to commenting your code, to know what is for the functions you're writing
I hope you helped to keep your code clean for further programming and happy coding!
You can use JS array functions like reduce(),split(),reverse(), etc. You can write the code in following ways:
function wordFlipper(word) {
return(word.split('').reverse().join(''));
}
function wordFlipper(word) {
return(word.split('').reduce((a,c)=>c+a));
}
Please go through the links for clarity on the functions used above:
split() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
join() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join
reverse() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse
reduce() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

Understanding the assignment operator - javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
In javascript my understanding of the assignment operator is that it is the = sign.
var x = 120
but if you then wanted to do a for loop using this variable, you would normally shorten it for example:
for (x = 120; x < 140; x++);
so in between the paranthesis,it appears that the < symbol is also an assignment operator, as it states it is less than 140 and should be increased to 140.
Could someone explain more clarity on this or point me in the right direction, as most things i find shows this rightfully as the less than operator.
Your function myfunction (i=1; i < thisVar; i++) is a syntax error. We can't explain how that code works because it doesn't.
You may be thinking of the for loop:
for (i=1; i < thisVar; i++) {
}
The for loop has three expressions within its () that are separated with ;:
An initialization (i=1 in your case) that occurs at the very beginning, before the first test (see #2)
A test (i < thisVar in your case) that is performed prior to each iteration of the loop and determines whether the loop ends
An update (i++ in your case) that occurs after each loop iteration, before the test
This is intrinsic to how for loops work, and is not general-purpose; you can't just do that within () anywhere you like, it has to be on a for loop.
The < in that, as you can see above, is part of the test — a condition that must be true for the loop to continue. It's not an assignment. It's a relational operator comparing i with thisVar to determine whether i is less than thisVar.

Why does Douglas Crockford write `if` conditionals that are executed everytime except the first? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I've been reading his book and he does stuff like this is a lot. For example, on p. 48 of JavaScript: The Good Parts, he has the function
Cat.prototype.purr = function ( n )
var i, s = '';
for ( i = 0; i < n; i += 1 )
{
if (s) {
s += '-';
}
s += 'r';
}
return s;
}
where the if conditional if essentially useless since it returns true every time but the first. The function could be written equivalently
Cat.prototype.purr = function ( n )
var i, s = 'r';
for ( i = 2; i < n; i += 1 )
{
s += '-r';
}
return s;
}
for better performance. Also, why does he define i outside the for loop?
The two functions are not the same. The original function returns an empty string of n is 0. Your function returns "r" if n is 0;
I am guessing that this is just an example to illustrate a common need where you want to separate a list of items with a character like '-' or ','.
You might write a loop like this and instead of 'r' you would have the names of items. E.g. "Bob-Mike-Jill-Jack"
To simplify the example for the book then he has just used 'r' which means the code could be written a different way like you say. But for a generic list you do want to add the separator every time except the first.
In regards to the var placement if you are declaring s then it is less chars to declare i there as well rather than write out var again in the loop. But I suspect it is probably just his idea of good practice to declare all variables that you use at the start of the function.

Superfluous curly braces [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have a student who likes to wrap large sections of code in curly braces so he can collapse those sections in the code editor. Initially, I balked at it, but couldn't think of a legitimate reason not to allow him to do it. I'm wondering if this practice will create any problems later on.
Example:
var a = 0;
var b = 1;
{ if (a == b){
alert("a = b");
}
else if (a > b){
alert("a > b");
}
else if (a < b){
alert("a < b");
}
}
I know there's a debate about braces around single statements inside an if, that's not what I'm talking about. I'm talking about the "parent" braces, if you will, around the series of if/else if statements.
As deceze indicated in his comment, you are incorrect about the braces limiting the scope of the variables.
var a = "outside";
{
var a = "inside";
var b = "another inside";
}
console.log(a); // prints "inside"
console.log(b); // prints "another inside"
Having said that, if you need to add in braces to make the code easier to navigate (read: ignore) it's a sign that the function is too long and should be broken apart into well named functions.

My first permutation lesson - what is this code missing? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Translated (apparently wrongly) from a C++ book.
If I can get it to work, then I can start trying to understand it.
function recPermute(soFar, rest)
{
if (rest==="")
{
console.log(soFar);
}
else
{
for(i=0; i<rest.length; i++) // <<< error was in not declaring the "i"
{
var next = soFar + rest[i];
var remaining = rest.substr(0,i) + rest.substr(i+1);
recPermute(next, remaining);
}
}
}
function listPerm(s)
{
recPermute("",s);
}
listPerm("kitcap")
You need to declare i so it's scoped to recPermute:
for(var i=0; i<rest.length; i++)
Without the var, it'll be created as a global so each call to recPermute will alter it for any other calls.
for JavaScript, use charAt(), instead of using array like acessing.
var next = soFar + rest.charAt(i);
One thing that could be an issue is you are using effectively the same i for each call to the function. You need to declare a local i or it will be declared in the global scope.
for(var i = 0; ....

Categories

Resources