Home » Tutorials » JavaScript » Variables

Variables

JavaScript is a very forgiving language and that includes its usage of variables. Variables are a container for unknown or known values. This means that you can change the value of a variable as many times as you wish. JavaScript variables are defined only using the word var before them.

Some Quick JavaScript Rules

  • JavaScript is case sensitive, which means “myVariable” is not the same as “myvariable”.
  • JavaScript, for the most part, ignores white space. Depending on the programmer, you might see var example = “pickles”; or you might see var example=”pickles”;. I am going to try to stay consistent with the first one.

A variable in JavaScript is simply declared by:

Example
<html>
    <body>
        <script type="text/JavaScript">
            var stringExample;
            var intExample;
        </script>
    </body>
</html>

Of course, we have only declared the variables in the example above. We have not set any value to them, which means that they are currently empty or null.

Example
<html>
    <body>
        <script type="text/JavaScript">
            var stringExample ="This is a string";
            var intExample = 7;
            var booleanExample = true
        </script>
    </body>
</html>

In the example above, we can see that the variable stringExample is set to “This is a string”, where the string must be in quotes. The intExample is set to 7, since 7 is a integer, it shouldn’t be in quotes. The booleanExample is set to true, since true is a boolean value. (Quick Note: true and false are the only two values a boolean can be set to.)

Variable Naming

Try to keep a consistent naming scheme when naming variables. Notice how I divided the “words” by lowering the first word and capitalizing the letter of the next word. Also, try to name variables with a sense of what their purpose is. An example would be var numberOfTurtles = 7.

References



Link/cite this page

If you use any of the content on this page in your own work, please use the code below to cite this page as the source of the content.

  • Stewart, Suzy. "Variables". After Hours Programming. Accessed on March 17, 2024. https://www.afterhoursprogramming.com/tutorial/javascript/variables-js/.

  • Stewart, Suzy. "Variables". After Hours Programming, https://www.afterhoursprogramming.com/tutorial/javascript/variables-js/. Accessed 17 March, 2024.

  • Stewart, Suzy. Variables. After Hours Programming. Retrieved from https://www.afterhoursprogramming.com/tutorial/javascript/variables-js/.



Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.