solaire solaire - 7 months ago 10
Javascript Question

In JavaScript console.log

I'm having trouble with the JavaScript syntax. Why does this work:

console.log($rootScope.wg.variable1);


But this doesn't (says its
undefined
):

console.log($rootScope.wg.variable+1);


I tried some other syntax, but could't find one which is working.

Answer

You need to use this in a different way:

console.log($rootScope.wg["variable" + 1]);

The reason is, variable1 is not the same as variable+1. This is nothing related to AngularJS, but it is basically how JavaScript's and other programming languages' concatenation logic works.

This is called as accessing key of an object, where $rootScope.wg is the object in the question.