Categories
JavaScript Tutorials

Variables

Naming a Value with an Identifier

So far, as the literals we have created thus far are anonymous, we have no way to query or manipulate their values later. To fix this, we need to name them with an identifier. Doing so creates a variable, which of course is a named value.

Type the keyword var followed by the identifier iceCream and a semicolon. Doing so declares a variable named iceCream to JavaScript. However, 

iceCream contains undefined, a literal conveying no value.

var iceCream;

Let’s put the string literal “Chocolate Fudge Brownie” in iceCream with the = operator:

var iceCream;
iceCream = "Chocolate Fudge Brownie";

To query the value contained by a variable, type its identifier. Type iceCream, and click Run.

JavaScript will then return the string literal:

var iceCream;
iceCream = "Chocolate Fudge Brownie";
iceCream;
// "Chocolate Fudge Brownie"

To put a new value in iceCream, do another = operation. So, let’s replace “Chocolate Fudge Brownie” with “New York Super Fudge Chunk” like so:

var iceCream;
iceCream = "Chocolate Fudge Brownie";
iceCream = "New York Super Fudge Chunk";
iceCream;
// "New York Super Fudge Chunk"


Rules for naming variables

JavaScript identifiers may only contain letters, numbers, and the _ underscore character. It can’t begin with a number, though. Identifiers may not contain whitespace, ones containing two or more words are written in camel case. That is to say, spaces are deleted, and the first letter in every word but the first is capitalized. JavaScript syntax, as defined by the ECMAScript standard, reserves the following identifiers, referred to as keywords. Keywords cannot be used as variables.

Variables are Case Sensitive

var case_matters = 'lower';
var Case_Matters = 'upper';
case_matters;
// "lower"
Case_Matters;
// "upper"