Page 125 - CITS - Computer Software Application -TT
P. 125
COMPUTER SOFTWARE APPLICATION - CITS
JavaScript uses the keywords var, let and const to declare variables.
An equal sign is used to assign values to variables.
In this example, x is defined as a variable. Then, x is assigned (given) the value 6:
let x;
x = 6;
Variables are Containers for Storing Data
JavaScript Variables can be declared in 4 ways:
• Automatically
• Using var
• Using let
• Using const
In this first example, x, y, and z are undeclared variables.
They are automatically declared when first used:
Example
x = 5;
y = 6;
z = x + y;
Note
It is considered good programming practice to always declare variables before use.
From the examples you can guess:
• x stores the value 5
• y stores the value 6
• z stores the value 11
Example using var
var x = 5;
var y = 6;
var z = x + y;
Note
The var keyword was used in all JavaScript code from 1995 to 2015.
The let and const keywords were added to JavaScript in 2015.
The var keyword should only be used in code written for older browsers.
Example using let
let x = 5;
let y = 6;
let z = x + y;
Example using const
const x = 5;
const y = 6;
const z = x + y;
112
CITS : IT&ITES - Computer Software Application - Lesson 37 - 46