Your browser does not support JavaScript!
Upvotes Anonymous 0 User 0

Variables in JavaScript

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.
So what exactly is a variable?
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.
What do variables store?
Variables can store strings (text):
var firstname = "Bob";
or numbers:
var numPeople = 3;
or objects:
var fruits = ['banana', 'pineapple', 'peach', 'strawberry'];
Was this helpful?

Tags

Comments

Leave a Comment

I agree to the Terms of Service
Design © 2015, Downranked, LLC.,
Original user code contributions under MIT License