It appears you have been introduced to the world of asynchronous JavaScript code. In this realm, not everything runs in a predictable order.
Take for example the following code snippet:
setTimeout(function(){
var test = 'hello';
console.log('first test : ' + test);
}, 1000)
console.log('second test : ' + test);
You'll observe that the second log statement will display nothing, despite the fact that 'test' was set earlier in the code. Even setting the timeout to 0 seconds will yield the same outcome. This behavior is a result of the event loop, which manages asynchronous operations by placing them at the end of the execution queue. Therefore, when the second console log is executed, 'test' has not yet been defined.
But why use asynchronous code? In web browsers, both UI rendering and JavaScript execution occur on the same thread. If a function like setTimeout were synchronous and blocked the thread for a set period of time, the entire UI would freeze. Asynchronous code allows for non-blocking operations, ensuring smooth performance even during tasks that take longer to complete, such as HTTP requests to servers.
Consider the following method that makes a request to a server:
UserService.getUsers().
success(function(data, status) {
$scope.users = data.users;
console.log($scope.users);
});
The code inside the success callback is also asynchronous. Any subsequent code after this call will execute immediately, while the content within the success function will run once the request has been fulfilled.
So, if you have something like:
fetchUsers();
console.log($scope.users);
Just remember that $scope.users will be populated only after the console log statement.