Tuesday, May 14, 2024

JS Variables

 

Variables are Containers for Storing Data

JavaScript Variables can be declared in 4 ways:

Automatically
Using var
Using let
Using const

Var Keyword:

The var keyword was used in all JavaScript code from 1995 to 2015.
The let and const keywords were added to JavaScript in 2015.
The var keyword should only be used in code written for older browsers.


<!DOCTYPE>
<html>
<head>
    <title>JavaScript</title>
    <script>
        var x = "Hello";
        var y = "World";
        document.write(x + y);
    </script>
</head>
<body>
</body>
</html>

 

Let Variable:

Variables defined with let cannot be Redeclared
Variables defined with let must be Declared before use
Variables defined with let have Block Scope


<!DOCTYPE>
<html>
<head>
    <title>JavaScript</title>
    <script>
        let z = "Hello World";
        document.write(z);
    </script>
</head>
<body>
</body>
</html>


Const Variable:

Variables defined with const cannot be Redeclared
Variables defined with const cannot be Reassigned
Variables defined with const have Block Scope


<!DOCTYPE>
<html>
<head>
    <title>JavaScript</title>
    <script>
        const second = "Hello World";
        document.write(second);
    </script>
</head>
<body>
</body>
</html>

No comments:

Post a Comment