...

Web Technologies - JAVASCRIPT

Back to Course

Lesson Description


Lession - #201 Javascript Variables


A variable is a symbolic name for (or reference to>
information. They are called variables because the represented information can change but the operations on the variable remain the same.

There are three different variable/javascript global variable types:
  • var
  • let
  • const
    Every one of these variables have a several rules around how they should to be used, and have various attributes .

    var

    Utilize the reserve keyword "var" to declare a variable in JavaScript. The default value of variables that don't have any value is undefined that is checked known as javascript undefined check. You can assign a value to a variable utilizing the = operator when you declare it or later the declaration and before to getting to it.
    javascript var vs let : let is limited to block in which it is declared but var is global scope.

    0
    
    <!DOCTYPE html>
    <html>
    <body>
    
    <h1>JavaScript Variables</h1>
    
    <p>In this example, x, y, and z are variables.</p>
    
    <p id="demo"></p>
    
    <script>
    var x = 4;
    var y = 3;
    var z = x + y;
    document.getElementById("demo">
    .innerHTML = "The value of z is: " + z; </script> </body> </html>

    Try it here

    let

    let permits you to declare variables that are restricted to the extent or scope of a block statement, or expression on which it is used.

  • Variables defined with let can't be Redeclared.
  • Variables defined with let should be Declared before use.
  • Variables defined with let have Block Scope.
  • Variables defined with let can't be redeclared.

    Let's see an example

    
    
    <!DOCTYPE html>
    <html>
    <body>
    
    <h1>JavaScript let Variable</h1>
    
    <p>Create a variable, assign a value to it, and display it:</p>
    
    <p id="demo"></p>
    
    <script>
    let carName = "Maruti";
    document.getElementById("demo">
    .innerHTML = carName; </script> </body> </html>

    Output


    Try it here

    const

    Constants are block-scoped, similar as variables declared utilizing the let keyword. The value of a const can't be changed through reassignment (for example by utilizing the assignment opeartor>
    , and it can't be redeclared (for example through a variable declaration>
    .

    Let's see an example

    
    <!DOCTYPE html>
    <html>
    <body>
    
    <script>
         const x = 16;
         document.write("The value of const variable x = " + x>
    ; </script> </body> </html>

    Output


    Try it here