Kévin Duguay
Kévin Duguay

Reputation: 761

Confuse terms in Angular JS tutorial

I'm following a tutorial and I have difficulties to understand a certain sentence which talks about the problem that can occur when naming my properties in Angular:

It quietly tolerates all property access errors, including nested properties on nonexistent parents and out-of-bounds array access.

aliasing variables as a way to cope with variable shadowing

My english is good enough to know what is written, but I really don't understand what is "nested properties on nonexistent parents" and "aliasing variables as a way to cope with variable shadowing". I did some research, but couldn't clearly understand.

Could someone give me a clear explanation?

Upvotes: 1

Views: 54

Answers (1)

UtsavShah
UtsavShah

Reputation: 877

Suppose you have:

obj : { 
    first: {
        second: [1, 2, 3]
    }
}

Trying to do this:

obj.nonexistent.prop // Nested property on nonexistent parent
obj.first.second[1000] // Out of bound array access

Would throw an error in javascript, but Angular doesn't throw an error

For aliasing variables as a way to cope with variable shadowing, imagine this:

<div ng-controller="ItemsController">
  <div ng-repeat="item in items" ng-init="outerCount = $index">
    {{outerCount + 1}}. {{item.name}}
    <div ng-repeat="item in item.items">
       {{outerCount + 1}}.{{$index + 1}}. {{item.name}}
    </div>
  </div>
</div>

From here

In an ng-repeat, the $index variable changes to point at the current index of the loop each iteration. So if you have nested loops, you'll lose a reference to the outer $index variable. This is variable shadowing. To use the outer variable, you can use ng-init and set it to the $index outside. Now, you've aliased the outer $index variable to outerCount.

Hope this is clear!

Upvotes: 1

Related Questions