3

var jem = 55;

var app = angular.module("store",[]);
app.controller("storeController",function(){
  this.product = jem;
});


jem = 0;
<!DOCTYPE html>
<html ng-app="store">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body ng-controller="storeController as store">
  <p>{{"HI"}}</p>
  <p>{{store.product}} </p>

</body>
</html>

Why does this output is "0" instead of "55"? Since jem is a basic javascript variable when product is assigned with jem it gets its value copied and should not change when jem is changed?

1 Answer 1

3

Notice that your controller definition is inside a callback function (as it should be...)

app.controller("storeController", function(){
  this.product = jem;
});

A side effect of this, relevant to your question, is that the assignment statement within the callback, this.product = jem, will get executed after the assignment statement, jem = 0, outside of the callback.

The takeaway is that callbacks do not take place sequentially with the rest of your code.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.