Variable types in JavaScript

Working with string, numeric and boolean variables, assigning values with the const and let keywords, and using the typeof opertor to investigate a variable’s type.

Learning Goals

At the end of this Lesson you will be able to:

  • Declare string and numeric variables and assign values to them with the let keyword.
  • Apply the correct variable naming standards
  • Perform addition, subtraction, multiplication and division on numeric variables
  • Follow the rules of operator precedence in arithmetic statements
  • Apply the assignment operator correctly in statements that contain variables and values, and variables only
  • Reveal a variable's type using the typeof operator.

In this Lesson you will meet the following terms:

  • Variable
  • String variable
  • Numeric variable
  • Assignment statement

Exercise File: Variable Types

About variables in JavaScript

You can think of a variable as a container or ‘storage box’ for a value that may be different each time the JavaScript code is run.

Consider the example of a website login page that asks for a user's First Name.

JavaScript

The value entered might be 'Mary' or 'John' or whatever. But in the JavaScript code that stores the value, the variable will always have the same name of, for example, userSurname.

In JavaScript the first thing you do with a variable is declare it. The following code declares the variable named FirstName.

var FirstName;

The declaration begins with the word var. This so-called keyword allocates memory storage space for new data and tells JavaScript that a new variable name is in use.

The more modern version of JavaScript uses the keywords const or let to declare a variable. For simplicity, the let keyword is always used in the examples in these Lessons. For example:

let FirstName;

Variable names

Here are a few points to remember about variable names:

  • Uniqueness: Don't use the same name for two different variables within the same JavaScript code.
  • No spaces: Variable names cannot contain spaces. ‘Credit Limit’ and ‘Sub Total’ are invalid variable names.
  • Mixed character case: You can combine upper and lowercase letters in a variable name to make it easier to read. For example, ‘PostCode’ and ‘AccountStatus'.
  • Case sensitivity: Variable names are case-sensitive. ‘Fname’ is not the same as ‘fName'.

When you have declared a variable you will typically want to assign data to it. The following two statements assign values to the variables named userName and userRegion.

let userName;
userName = "Sheila";
let userRegion;
userRegion = "Australia";

You can minimise typing by declaring a variable and assigning a value to it in the same statement on the same line. Here's two examples.

let UserID = "289849";
let Password = "banana42";

In Exercise 3.1 you will declare two variables, assign values to them, and then display the variable names and values in the web page.

Exercise 3.1: Displaying string variables

In the first js-box DIV, enter the following statement inside the <script> tags:

let FirstName = "Eddie";
let Surname = "Hamilton"
document.write("<i>First Name:<\/i> "+FirstName+"<br>");
document.write("<i>Surname:<\/i> "+Surname);

Save and reload your web page. The result should look as shown below.

JavaScript

About string variables

The variables you have worked with so far have all been of one type: the string variable. This is a variable type that holds letters, numbers, white (blank) spaces or punctuation symbols.

When you enclose the value in quotes JavaScript assumes that you want to create a string variable. For example:

let FirstName = "Peter";
let StreetAddress = "42 Green Avenue";
let PhoneNumber = "045 45773758752";

About numeric variables

Another type of variable in JavaScript is the numeric variable, which stores a number that you can perform arithmetic operations on

When you omit the quotes around the value, JavaScript makes the variable a numeric variable. For example.

let OrderQty = 4;
let productPrice = 9.9;

Consider the following example:

  • When you assign ‘15’ as a string variable JavaScript stores the ‘1’ and the ‘5’ as keyboard characters in the same way as it would store the characters ‘a', ‘z’ or ‘@'.
       let myVar = "15";
    
    You would store telephone numbers in JavaScript as string variables because you will never want to perform arithmetic on them, such as dividing a telephone number by two.   Don't assign a number to a string variable if you intend using that number in a calculation.
  • When you assign ‘15’ as a numeric variable, however, JavaScript stores ‘15’ as a number that can be manipulated by a script in combination with other numeric variables.
       let myVar = 15;
    

Unlike most programming languages JavaScript does not have different types of numeric variables for different types of numbers. All numbers, whether integers (whole numbers) or floating-point numbers (numbers with decimal places) are all stored within the one type of numeric variable type. Numeric variables may store ether positive or negative numbers.

Here are two values that JavaScript will accept as valid numbers.

let Temperature = -6.3456
let errorRare = .2727

And here are two values that are not valid numbers in JavaScript.

let userIncome = 34,000 // Error. Contains a comma.
let product ID = 645w29 // Error. Contains a letter character.

When creating a variable you don't need to tell JavaScript whether the variable is to be string or numeric. JavaScript decides the type of variable you want according to whether or not you entered its value within quotes (string variable) or not (numeric variable).

Variable

A container that can store a changing value. A variable may contain strings or numbers. Variable names must be unique, are case sensitive and cannot contain spaces.

In Exercise 3.2 you will declare three variables, assign numeric values to the first two, add the values together and assign the result to a third variable. Finally, you will then display all the numbers in the web page.

Exercise 3.2: Adding Numeric Variables

In second js-box DIV, enter the following statement inside the <script> tags:

const firstNumber = 36;
const secondNumber = 12;
const sumResult = firstNumber + secondNumber;
document.write("<p>First Number: "+firstNumber+"<br>");
document.write("Second Number: "+secondNumber+"<br>");
document.write("Result: <b>"+sumResult+"</b></p>");

Save and reload your web page. The result should look as shown below.

JavaScript

Experiment with the file by changing the first and second number values, and by changing the arithmetic operator. You can close the exercise-3-2.html file when finished.

About the assignment (=) operator

Putting a value into a variable is known as assignment, and is achieved through the use of the assignment operator (=). For example:

fruit = "apple";

This places the value of ‘apple’ inside the variable named ‘fruit'.

In JavaScript the equals sign does not mean 'equal to' as it does in arithmetic or algebra. It means as follows:

‘Take whatever is on the right of the equals sign and place it in variable on the left hand side.'

JavaScript treats the left-hand side (LHS) as a variable, but the right-hand side (RHS) may be a value, another variable, or an object property. In the example below the RHS contains a value.

country = "Bermuda";

Sometimes you may want to change a variable's value by a fixed amount. The following would make no sense if it where algebra.

productPrice = productPrice + 20;

But in JavaScript it means ‘jack up the product price by 20%. That is, insert in the productPrice variable whatever is currently in that variable already plus 20.

Assignment statement

A JavaScript statement in which a variable or object property on the left of the equal sign (=) is given the value of whatever is on the right of the equals sign.

Automatic variable retyping

JavaScript, as you have learnt, decides which type of variable you want to create by the way that you first assign a value to it. When you enclose the value within quotes, JavaScript makes the variable a string variable; when you omit the quotes, JavaScript makes it a numeric variable.

JavaScript can also change the type of a variable when you assign a value of a different type to that variable. It's called automatic type conversion. Consider the following two statements.

let myvar = "12.34";
myvar = 12.34;

In the first statement JavaScript makes the variable named ‘myvar’ a string variable. In the second statement JavaScript changes the variable type to numeric because a number was assigned to it.

Automatic variable type conversion is a powerful feature of JavaScript, but its very power can result in scripting errors or in scripts that produce unexpected results. You need to be particularly careful with variables types when dealing with HTML forms that accept input from web page visitors. Because forms accept input as strings you need to convert such strings to numbers when you want to include them in arithmetic calculations.

The typeof operator

When you are unsure about variable type at any some point in a script you can use the typeof operator to reveal the variable type. You insert the typeof operator directly before the variable. Here are three statements in which the typeof operator is used within a document.write() statement.

document.write(typeof SalesPrice);
document.write(typeof x);
document.write(typeof email_address);

Exercise 3.3 takes you through the steps setting, changing and displaying a variable's type.

Exercise 3.3: Investigating a variable’s type

In third first js-box DIV, enter the following statement inside the <script> tags:

let firstVar;
document.write("<b>Variable Type:<\/b> " + typeof firstVar);

Save and reload the web page. In the browser window you can see that the variable type is 'undefined'. This is because you have only declared the variable but not assigned a value to it.

JavaScript

Next, replace everything within the <script></script> tag pair with the following code.

let firstVar;
document.write("<p><b>Variable Type:<\/b> " + typeof firstVar+"<\/p>");
document.write("<p><b>Variable Type:<\/b> " + typeof firstVar+"<\/p>");
document.write("<p><b>Variable Type:<\/b> " + typeof firstVar+"<\/p>");
document.write("<p><b>Variable Type:<\/b> " + typeof firstVar+"<\/p>");

Save and reload your web page. You can see the result of four document.write() statements, each one displayed on a separate line.

JavaScript

Now, add three assignment statements to your block of code at the locations shown below.

JavaScript

Save and reload your web page. It should now look as shown below.

JavaScript

You can see how the variable's type changed during the script: from undefined (no type), to numeric, then to string, and finally back to numeric again.

You can close the file when finished.

Boolean variable type

A third type of variable in JavaScript is the Boolean variable. This may have one of only two possible values: true or false.

Developers typically give Boolean variables names such as isCustomer, isLoggedIn, isSelected, and so on.

 

 Back to Top