Variables
Learn about and practice with variables in JavaScript.
We'll cover the following...
Variables are used in programming languages to refer to a value stored in memory. They give us a convenient way to refer to different values in a program. They can be thought of as labels that point to different values. Variables are a useful way of dealing with long expressions because they save us from typing these expressions over and over again.
Declaring and assigning variables
In most programming languages, variables have to be declared before they
can be used. That is, they need to be explicitly referred to in the code, and
possibly assigned a value.
In a strongly typed language, the type of the variable has to be declared with
the variable. For example, if we were going to use the variable yourName
for the
string Homer Simpson
, we might use the following code in a strongly typed
language:
let yourName:string = "Homer Simpson";
This not only sets the variable yourName
to point to the string Homer Simpson
,
but also declares that this variable will be a string. This will result in an error if we try to assign the variable to another value that is not a string later in the
program.
Weakly typed programming languages don’t insist on explicitly stating what
type a variable is when it’s declared. The type is said to be implicit from the
actual value that’s assigned to it, although we could theoretically assign the
variable to a different type later in the program without any problems. In a
weakly typed language, the following code might be used to set the variable
yourName
to be the string Homer Simpson
:
yourName = "Homer Simpson";
This still has the same effect of pointing the variable yourName
to the string
Homer Simpson
, but it doesn’t ...