Javascript declaring a variable inside the initialization step - javascript

I am watching a video about C programming, and the instructor has an example for loop that is written as such:
for(int i=0, n=strlen(c); i<n; i++)
In Javascript can we declare n in the same way as well? I'm trying to not set "i
Edit:
Thank you for the replys. Sounds like I can't do the code from above, but instead I would have to split it up into 2 separate line items like so:
const n = strlen(c);
for(int i=0; i<n; i++)

In Javascript can we declare n in the same way as well?
Yes. You can use either var or let there, and it makes a big difference: Inside the loop's block, if you use var, all loop iterations share a single variable. If you use let, each loop iteration gets its own variable. This only matters if you create closures within the loop.
Example of the difference:
for (var varvar = 0; varvar < 3; ++varvar) {
setTimeout(() => {
console.log(`varvar = ${varvar}`);
}, 10);
}
for (let letvar = 0; letvar < 3; ++letvar) {
setTimeout(() => {
console.log(`letvar = ${letvar}`);
}, 20);
}
(And if you use var, the variable exists throughout the function [or global scope, if you're doing this at global scope]. With let, it's confined to the for loop.)

for(let i = 0; i < c.length; i ++)

Related

Why does i = 3 outside the for loop?

The condition in the loop specifies i<3. Shouldn't the loop stop at i = 2? if so, shouldn't outside loop be 2 not 3?
Thanks.
for (var i = 0; i < 3; i++){
console.log(i, " loop")
if(i%2===0){
console.log (i,'even numbers in loop ');
}
}
console.log(i, " outside loop")
That's the correct behaviour of loops.
The loop starts with i = 0, then i = 1, then i = 2, then i = 3. oops i is no more less than 3, break the loop. that's what's going on, so when you log the value of i you get 3 and not 2.
Loop: it breaks as soon as i < 3 is not verified, which means in the last iteration. More informations about iterations.
Scope: because i is declared using var, which attaches the variable to the global scope. Using var is highly discouraged, use let instead, which declares variables in block scope. More informations about var and let.

ES6 javascript block scope variable hoisting into for header

Are all of the block scope variables in a for loop block hoisted above the loop header itself?
var x = 4;
for(let i = 3; i < x; i++) {
let x = 2;
...
}
Should this produce a dead-zone error on x every time i is compared to x in the loop header? I understand i is pushed down in the block scope, but why not x?
The relevant section of the language specification is 13.7.4
If the for statement contains a let or const declaration then a scope is created.
Each iteration creates a scope, if the for statement contains a let declaration.
If the for body is a block then a scope is created.
Here are some examples and the scopes that are created:
//no scope
for(i = 0; i<3; i++) console.log(i);
//no scope
for(var i = 0; i<3; i++) console.log(i);
//for scope and iteration scope
for(let i = 0; i<3; i++) console.log(i);
// for scope, iteration scope and block scope
for(let i = 0; i<3; i++) {
console.log(i);
}
Why do we need iteration scopes? For closures:
for(let i = 0; i<3; i++) {
setTimeout(() => console.log(i), 10);
}
Output without iteration scope: 3,3,3. With iteration scope: 0,1,2
based on that, i think let x are only available in that for scope.
Are all of the block scope variables in a for loop block hoisted above the loop header itself?
No, they are hoisted in the block scope
Should this produce a dead-zone error on x every time i is compared to x in the loop header? I understand i is pushed down in the block scope, but why not x?
No, because x in the loop header is referencing x defined as 4 var x = 4
You cannot access a let variable before it has been declared as that time between scoping and declaration is the TDZ.
ex.
console.log(x) // Reference Error, x is in TDZ
let x = 4
console.log(x) // --> 4
I misunderstood, and thought that there would be only one block scope. I balked at taking the two arbitrary variables in the expression i < x and having to decide which block scope to look them up, which is impossible to determine.
The correct approach is to build two nested block scopes, one for the loop header and one for the loop body. That means let i is seen in both the loop header and the loop body scopes, and the let x in the loop is only seen in the loop body scope. Easy peasy, lemon squeezy.

Object.create to create an object with costructor

I am learning Javascript and I am a C++ programmer. I have tried creating an object with a constructor with object.create and here is the result:
var PlayGround ={
initGrid : function(N) {
this.N=N;
this.grid = new Array(N);
for (var i = 0; i < N; i++) {
this.grid[i] = new Array(N);
for (var j = 0; j < N; j++) {
this.grid[i][j] = false;
}
}
return true;
}
};
var PlayGround_property = {
N:{
value: 100,
writable:true
},
grid:{
value:null,
writable:true
}
}
var board= Object.create(PlayGround, PlayGround_property);
It works as I want: the object board contains the object grid, and now I can use the set and get keyword to define the behaviour of the = and () operator.
Anyway I have read around the web that the
this
keyword in Javascript is not safe and I want to be sure that it is referring always to the board object and not to the global window object. Is there a way or I am overthinking?
Other question, are there other ways to write object with a constructor (and maybe other members) in Javascript?
I want to be sure that [this] is referring always to the board object
A function's this is set either by how you call the function, or bind. So just make sure you call methods the right way. If you always call functions as methods of board, then this within the methods will always reference board.
If you are only going to have one instance of board, there doesn't seem much point in using a constructor. If you have multiple instances of board, then you want this to reference the particular instance that called the method so you don't want to fix this using bind.
Crockford just doesn't like the use of new, so encouraged Object.create, it fits his idea of how inheritance should work.
Your pattern could be rewritten to use a constructor something like:
function PlayGround (N) {
this.N = N;
this.grid = []; // Use array literal, it's less to type
for (var i = 0; i < N; i++) {
this.grid[i] = [];
for (var j = 0; j < N; j++) {
this.grid[i][j] = false; // Not sure why you bother with this
}
}
}
var board = new Playground(100);
I'm not exactly sure what you're doing, but that should be close. Note that javascipt is loosely typed, so only initialise variables and properties if you have something useful to assign. Variables are created with a value of undefined, Array properties are only created if you actually assign something to them, creating an array with length N does not create any indexes, e.g.
var arr = new Array(10);
console.log(arr.length); // 10
console.log(arr.hasOwnProperty(0)); // false

How to create closure in loop and store it in variable for later execution

See code below. I've tried to strip it to its bare bones.
I have a _queue array. I want to iterate 10 times. On each iteration, I want to create a function that has a properly scoped reference for j (i.e. j=0 on the first iteration, j=1 on the second iteration, etc.)
I want to store that function in variable f, and then add f to the _queue array so I can call it later.
The problem of course is that on each iteration of the first loop, instead of storing the closure in f, it immediately executes the closure.
My question is this: How do I store the function with its proper j variable so that I can add it to the _queue array?
_queue = [];
for (j = 0; j < 10; j++) {
var f =
(function (index) {
alert(index);
})(j); //code is executed here instead of stored in the f variable
_queue.push(f); //Add f
}
for (k = 0; k < _queue.length; k++){
_queue[k].call();
}
Using an immediate function (or in general using a function) to introduce a new scope is correct. But you have to return a function from the immediate function:
var f = (function (index) {
return function() {
alert(index);
};
}(j));

JavaScript setting variables?

Can someone explain the second line of this function? is it setting two variables to = 0 at one time? i.e. var i = 0 and var res = 0? If so, is it necessary to set var i = 0 considering that it does that in for(i = 0 ... etc
function sumOnSteroids () {
var i, res = 0;
var number_of_params = arguments.length;
for (i = o; i < number_of_params; i++) {
res += arguments[i];
}
return res;
}
No, the value of i will be undefined, the initializer only applies to "res" in that case. To assign the value you'd need:
var i = 0,
res = 0;
It is setting two variables at once with the var keyword being applied to both, scoping them. Without the var, they would be properties of window (essentially globals).
The first one (i) would be undefined and the second one (res) would be 0.
This is a powerful pattern because...
var should be implicit, but it is not, so we only have to repeat it once.
Less typing for you.
Better for minifying (smaller file size).

Categories

Resources