/  Technology   /  const Variable
c1

const Variable

 

What is const?

To store the constant variable values the const keyword is used. Variables defined with the const keyword cannot be redefined & cannot be reassigned.

The main advantage with const is that it prevents the variable to be assigned to another value.

In Real-time scenario const keyword is used to assign pre-defined math values, IP address of users and so on, which should be unique values.

Const is mainly used when we need to assign a values which should not be modified.

In JavaScript const variables must be assigned a value when they are declared otherwise it throws an Uncaught Syntax Error.

<html>
<title>
    Re-declaring a Variable Using const keyword
</title>
<body> 
    <script>
        const name;
        name="sailaja";
        document.write(name)
    </script>
</body>
</html>

Output:

c2

Redefining of const variable throws an Uncaught Syntax Error.

<html>
<title>
    Redefining a Variable using const keyword
</title>
<body> 
    <script>
        const name="sailaja";
        document.write(name)
    </script>
    <script>
        const name="sailaja";
        document.write(name)
    </script>
</body>
</html>

Output:

c3

 

Leave a comment