Programming Examples

Are you a Programmer or Application Developer or a DBA? Take a cup of coffee, sit back and spend few minutes here :)

JavaScript 001 – Declare Variable

1. Declare Variable in JavaScript

In JavaScript, you can declare a variable using the var keyword. This tells the system to reserve some memory for future use. After declaring the variable, we can store a value in it. For example:

In the above snippet, we declare a variable called MyVar using the keyword var. In the next line, we store a value of 12 into the variable MyVar. The = sign denotes the assignment. Means. It tells value 12 is assigned to the variable MyVar. Note, JavaScript is case sensitive and when you read the back the value you have to use the same variable name with the same case.

2. The Declare Variable Example

The example is in the below screenshot. You can use any editor type the code and save it as 001_DeclareVariable.html:

First Java Script - Declare Variable
First Java Script – Declare Variable

Explanation

1) Within the body tag, we have a pair of <Script> & </Script> tags and the JavaScript code stays in between these tags.

2) In the first code snippet, we declared a variable called MyVar. Using the assignment operator =, we stored a string value in the MyVar. Then, using the alert function, we display the content of the MyVar in a message box. Note how semicolon in separating each statement for easy readability. But the usage of the semicolon to separate the statement is optional.

3) In this code snippet, we reuse the same variable MyVar and assign an integer value of 108 to it. JavaScript is a weekly typed language. So once a variable is declared, it can store any value in it. Here, in our case, the old value “Some String” is lost, and the variable is now holding the value 108 in it. We once again use the alert method to display the content of the variable, MyVar.

3. Running the Javascript Variable Example

1) Let us assume that you saved the file 001_DeclareVariable.html at C:\Temp folder.

2) Open Google Chrome Browser

3) Navigate to the Folder C:\Temp

4) Drag & Drop the File 001_DeclareVariable.html to Chrome Browser

5) The browser shows the Message Box thrown by the alert call. Message box shows the MyVar variable content:

Javascript Screen 1
Javascript Declare Variable Screen 1

6) Click OK on to the message box. The second alert display which shows the MyVar variable’s updated content:

JavaScript Screen 2
JavaScript Screen 2

4. Code Reference

001_DeclareVariable.html

Categories: JavaScript

Tags: ,

Do you like this Example? Please comment about it for others!!

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