Introduction
In the previous chapter, we learned how to enable or disable HTML Anchor Links (HyperLink), using JavaScript and jQuery.
In this chapter, we will learn about the basic concepts of JavaScript, the most important being variables and data types.
Variable
A Variable is an identifier or a name that is used to refer to a value. It is media to store the information to be referenced and manipulated in a computer program. Using the key of a variable in JavaScript “var”, the extension is important (.js).
Syntax
- var <variable-name>;
- var <variable-name> = <value>;
Note
In the example, the number 10 is assigned to “a”. Use only the special characters (__) underscore and ($) symbol, don't use other special characters like @, *, %, #. JavaScript is case sensitive.
In this example the variable name ‘a’ is uppercase,
- var a=10;
- document. Write(A); //varible name is lowercase
Error - ‘a’ is not found
Example 1
- <!DOCTYPE html>
- <html>
- <head>
- <title>Java Script</title>
- </head>
- <body>
- <h4>Variables in JavaScript</h4>
- <script>
- var a = "30";
- document.write(a);
- </script>
- </body>
- </html>
Output
Example 2
- <!DOCTYPE html>
- <html>
- <head>
- <title>Java Script</title>
- </head>
- <body>
- <h4>Variables in JavaScript</h4>
- <script>
- var name = "vijay";
- document.write(name);
- </script>
- </body>
- </html>
Output
There are two types of Variables
- Local Variable
- Global Variable
JavaScript Local Variable
The local variable is a variable in which a variable can be declared within the function, and it can be used only inside that function. So, variables with the same name can be used in different functions.
Example
//local Variable
- <!DOCTYPE html>
- <html>
- <head>
- <title>Java Script</title>
- </head>
- <body>
- <h4>JavaScript</h4>
- <script> // local variable
- function article (){
- var name = "Variables in JavaScript"; //inside the function declare a variable
- document.write(name);
- }
- article();
- </script>
- </body>
- </html>
Output
Global Variable
The global variable is a variable in which variables can be defined outside the function. So, variables with the same name cannot be used in different functions.
Example
//Global Variable
- <!DOCTYPE html>
- <html>
- <head>
- <title>Java Script</title>
- </head>
- <body>
- <h4>JavaScript</h4>
- <script> //global variable
- var articlename = "variables in JavaScript"; //outside the function declare a variable
- function article ()
- {
- document.write(articlename);
- }
- article();
- </script>
- </body>
- </html>
Output
Summary
In this chapter, we learned about variables in JavaScript, the scope of Variables, and how to declare a variable in JavaScript.