Variables and data types
Coding with JavaScript
🕑 This lesson will take about 20 minutes
In this second lesson from the beginner JavaScript coding course, you will learn how to create variables and work with strings, integers, float, and boolean data types in JavaScript.
Variables are used to store information in a program such as text, numbers or true/false values. Variables are given a name and are assigned a value to store. To create a variable in JavaScript we use the var keyword followed by a name we want to give the variable. A variable does not need to be given an initial value to store and can be given a value later in the code, for example, var score;
On the other hand, we can also give a variable an initial value to store when the variable is created. We can use the = sign followed by the value we want to store in the variable. For example, var score = 0;
Variable names must be unique and cannot contain spaces. They can’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. myVariableName, or by using underscores between each word.
Variables can store data values of different types. The main types are:
string – text values 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 two videos below to learn how to create and use variables of different data types, and then scroll down to view the sample code.
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 (lines of code beginning with // ) which explain the different ways of setting up variables. Note that the HTML file references the separate JavaScript file called script.js in the <head> section.
Here is the sample HTML and JavaScript code.
Tip: Check out the toFixed() method if you wish to display floats with a specified number of decimal places.
Next lesson: Arithmetic