Variables and Data Types in JavaScript

In this second video from the beginners JavaScript tutorial series, you will learn how to create variables and work with strings, integers, and float data types in JavaScript.

Variables are used to store information in program such as text, numbers or true/false values. Variables are given a name and are assigned a value. To create a variable in JavaScript we use the var keyword, then specify the variable name, use the = sign to assign a value, and then specify the value to store (you can also create a variable without immediately assigning it a value). For example: var myNumber = 50;

Variable names must be unique and cannot contain spaces. They don’t begin with a number but can contain numbers. They generally begin with a lowercase letter and if the variable name contains multiple words, then they can be indicated by using camelcase (starting each new word with an uppercase letter) eg. myVariable.

Variables can store data of different types. The main types are:

  • string – text including letters, numbers and other special characters eg. “Hello world”
  • integer – whole number values eg. 5
  • float – numbers with a decimal point eg. 5.3
  • boolean – a true or false value

 

Watch the video below and then scroll down to view the sample code.

The code snippets below show how to declare variables in JavaScript, how to assign values to a variable, and how to display variable values to the user. Pay attention to the //comments which explain the different ways of setting up variables.

Here is the HTML code:

<html>
    <head>
        <title>Variables</title>

        <script src="script.js"></script>
    </head>

    <body>
        
    </body>
</html>

And here is the JavaScript code:

// Data types in JavaScript:
// String - characters (letters, numbers, or symbols)
// Integer - whole numbers
// Float - floating point (decimal) numbers
// Boolean - true/false only

// These are string variables:
var user = "Joe";
var greeting = "Hello there";

// This is an integer variable:
var score = 50;

// This is a float variable:
var average = 20.57;

// This is a boolean variable:
var finishedGame = false;

// Example of joining (concatenating) variables and strings together to display on screen
// You can use , or + to join variables or strings together
document.write(greeting + ", " + user + ". Your score is " + score , ". The average score is " + average);

// You can mix HTML tags in JavaScript stings:
document.write("<h1>Welcome, " + user + ".</h1>");

// Make sure you escape quotes within a string using the \ backslash character
document.write("He said \"hello\".")

 

Hint: Have a look at the toFixed() method if you wish to display floats with a specified number of decimal places.

Next tutorial: Operators

Leave a Reply