Here is an example of a variable:
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<script>
var greeting = "Hello";
alert(greeting);
</script>
</body>
</html>
Here's what the page does:
This:
var greeting = "Hello!";
stores the text Hello! into a variable named greeting. The semicolon ; is used to indicate the end of a statement (instruction).
This line:
alert(greeting);
uses a function to show the user a message. We'll learn about functions later.
A variable is a way to store a value (number, text, etc.). The reason we store values is to help us do things with those values.
Analogy: People have names, and those names are used when you want to refer to a specific person. A variable is a way to give a name to a value, so you can refer to it later.
Variables can store strings (text):
var firstname = "Bob";
or numbers:
var numPeople = 3;
or objects:
var fruits = ['banana', 'pineapple', 'peach', 'strawberry'];
Next: JavaScript Functions
Leave a comment