Skip to main content

Javascript ECMAScript6 New Feature

ECMAScript 6 Const



Const

In ECMAScript 6 we have const variable arrived. Does it work the same as C++ const?
Not exactly. I would even say, “not at all”.
When you declare something with 
const in ECMAScript 6, it means that the identifier can’t be reassigned. 

What does it mean? 

It means that you cannot declare that variable more than once. Because its binding is immutable
You have guaranty that no rebinding will happen to it. 
You will not be able to change its type.
If your const variable is a simple value, like stringnumberboolean etc. you also wouldn’t be able to change its value.
So let’s look how does it work:

Declaration

Very simple. Just use const instead of var :
    const brandColor = 'turquoise'; 
The value of a constant doesn’t have to to be known at compile time, but you must assign it a value exactly once.

Const and scopes

Redeclaring:

Constants can’t be redeclared.
    const num = 1;
    //1
    const num = 2;
    //Uncaught TypeError: Identifier 'num' has already been declared(…)

Function scope:

You can declare const inside the function scope with the same as outside it, but you actually have local scoped const.
    const num = 1;
   
    function setNum(){
        const num = 2;
        console.log(num);
    }
   
    setNum();
    //2;
   
    console.log(num);
    //1;
You cannot reach const outside scope:
    if(!num){
        const num = 2;
    }
    console.log(num);
    //Uncaught ReferenceError: num is not defined(…)
Ok that’s easy. But also you cannot reach const by this, because it is block-scoped:
    const date = new Date();
   
    console.log(this.date);
    //undefined

Deleting and changing value of const

You cannot change value or delete a simple constant variable.
    const a = 1;
   
    a++;
    //Uncaught TypeError: Assignment to constant variable.(…)
   
    delete a;
    //true
   
    console.log(a);
    //1

Const Objects

If you declare const Object, you will not be able to delete it, or make it array or string, but you will be able to declare, change and even delete values of your constObject.
    const params = {
        size: 2,
        color: 'gray'
    }
   
    params = {};
    //Uncaught TypeError: Assignment to constant variable.(…)
   
    params.size++;
    delete params.color;
   
    console.log(params)
    //Object {size: 3}
But there is the way to freeze the Object with its values:
    const obj = Object.freeze({
        'num': 3
    });
    obj.num = 4; //throws error

So where to use const ?

Use const when you don’t need reassign the identifier. In practice it is becoming the brand new var for objects and arrays.
Because if you need to change type of any of them, it seems you wrote bad, not semantic code.


Comments

Popular posts from this blog

Claims Class For security in .NET4.5 with C#

What is Claim ? A claim in the world of authentication and authorization can be defined as a statement about an entity, typically a user. A claim can be very fine grained: Ram is an admin Ram’s email address is Ram@yahoo.com Ram lives in Mumbai Tom’s allowed to view sales figures between 2009 and 2012 Tom’s allowed to wipe out the universe Claims originate from a trusted entity other than the one that is being described. This means that it is not enough that Tom says that he is an administrator. If your company’s intranet runs on Windows then Tom will most likely figure in Active Directory/Email server/Sales authorisation system and it will be these systems that will hold these claims about Tom.  The idea is that if a trusted entity such as AD tells us things about Tom then we believe them a lot more than if Tom himself comes with the same claims . This external trusted entity is called an  Issuer . The KEY in the key-value pairs is called a  Typ...

How to do auto logout and redirect to login page when session expires using asp.net?

In this article I will explain you how to auto logout and redirect to  login page when users session expires within specific period. Introduction In every applications, we need to maintain the session expiration time  say for example 1hr or 30 minuets and this configuration item we  can do with web.config file or in IIS. But here, application should  redirect to login page automatically when session expires. Configure session time First configure the session timeout value in web.config file as like  below, here I’m configuring the session timeout value as 3 minutes  for this sample . < system.web > < sessionState mode = " InProc " timeout = " 3 " ></ sessionState > </ system.web >   Create Pagebase class create a custom pagebase class and write the common functionality codes into this class. Through this class, we can share the common functions to other web pages. In this class we need...

Javascript ECMAScript6 New Feature

Extended Parameter Handling Another nice set of features introduced in ES6 is the extended parameter handling. These provide a very nice set of idioms that bring us very close to languages like C# or Java. Default parameter values and optional parameters Default parameters allow your functions to have optional arguments without needing to check arguments.length or check for undefined. Let’s take a look at what that might look like: let greet = (msg = 'hello', name = 'world') => {   console.log(msg,name); } greet(); greet('hey'); Looking at the preceding code, you can see that we are using the new fat arrow (=>) syntax as well as the new let keyword. Neither of those are necessary for this example, but I added it to give you more exposure to the new syntax. Running the preceding code produces the following result: hello world hey world  Rest parameter Handling a function with a variable number of arguments is always t...