Reputation: 13
function analyse(data) {
var counter = 0;
for (let i = 0; i < data.length; i++) {
if (data[i].closed == true) {
counter++;
}
}
$scope.totalOpen = data.length - counter;
$scope.totalClosed = counter;
}
I am writing a simple function that iterates an array and increment counter
if the object inside the array's value is true. However, looks like the counter
variable inside the if
statement does not have the same scope as a counter
variable just above for
loop. Therefore, totalClosed
variable only gets assigned zero even though there are some objects those have closed as true
. I think I am not understanding the concept of scoping in Javascript properly. Can anyone help me out, please?
Upvotes: 1
Views: 2904
Reputation: 7368
JavaScript has two scopes – global and local. Any variable declared outside of a function belongs to the global scope, and is therefore accessible from anywhere in your code. Each function has its own scope, and any variable declared within that function is only accessible from that function and any nested functions. Because local scope in JavaScript is created by functions, it’s also called function scope. When we put a function inside another function, then we create nested scope.
There is no problem with your counter scope.This is a working sample based on your question:
data=[
{
"closed":true
},{
"closed":false
}]
function analyse(data) {
var counter = 0;
for (let i = 0; i < data.length; i++) {
if (data[i].closed == true) {
counter++;
}
}
var totalOpen = data.length - counter;
var totalClosed = counter;
console.log(totalClosed);
return totalClosed;
}
console.log(analyse(data))
Upvotes: 0
Reputation: 161
To build on @Taplar's side note, you could accomplish this goal more cleanly with a filter:
function analyse(data) {
var closedItems = data.filter(function (item) { return item.closed });
var totalClosed = closedItems.length;
var totalOpen = data.length - totalClosed;
console.log(totalOpen)
console.log(totalClosed)
}
Or, in ES6 syntax:
const analyze = (data) => {
const closedItems = data.filter(item => item.closed);
const totalClosed = closedItems.length;
const totalOpen = data.length - totalClosed;
return {totalOpen, totalClosed}
}
Upvotes: 1