Thursday, November 7, 2013

ECMAScript 6 - What's new in JavaScript - part 2 - const

Like I mentioned here: http://frontenddevs.blogspot.com/2013/09/ecmascript-6-whats-new-in-javascript.html I preparing series of posts about coming ECMAScript version 6.



Today I will write about const.



Some of you probably will know this special keyword from other languages. For people who don't know yet here are some explanations from MSDN page about const in C#:

The const keyword is used to modify a declaration of a field or local variable. It specifies that the value of the field or the local variable is constant, which means it cannot be modified. 

End of theory. Let's check it. First very basic example:

(function () {
  var foo = 'foo';
  const bar = 'bar';
  buzz = 'buzz';

  console.group('Before changes');
  console.info("inital value of foo:", foo);
  console.log("inital value of bar:", bar);
  console.log("inital value of buzz:", buzz);
  console.groupEnd('Before changes');

  foo += buzz;
  bar += buzz;
  buzz = null;

  console.group('After changes');
  console.log("here is foo:", foo);
  console.log("here is bar:", bar);
  console.log("here is buzz:", buzz);
  console.groupEnd('After changes');
})();

and here is the output of console:

Like you can notice we can change value of foo which is local variable, buzz which is global variable but cannot change value of bar because it const.

Here are another tries to change bar variable:
  bar = 'foo';
  console.log('Re-assign try: ', bar);

  const bar = 'foo';
  console.log('Re-initialize try: ', bar);

  var bar = 'foo';
  console.log('Re-declare try: ', bar);

and the output:
Uncaught TypeError: Variable 'bar' has already been declared

It's caused by trying of re-initialize and re-declare variable bar. So 2nd and 3rd try throw error but 1st still not changing value of bar.

And that's the point. Because const mean something constant it cannot be changed in scope where const value was declared.

Here you can find more examples of const:

No comments :

Post a Comment