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:

a web page with an alert dialog showing

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'];

Next: JavaScript Functions

Comments

Leave a comment

What color are brown eyes? (spam prevention)
Submit
Code under MIT License unless otherwise indicated.
© 2020, Downranked, LLC.