Variables and Simple Data Types
Variables
Variables are a JavaScript developer's bread and butter. They make it really easy to write complex programs with lots and lots of instructions, and keep everything organized and straight. Often times when you're writing a program in JavaScript, there will be several pieces of data that you need to keep track of. Think for example of Facebook. Facebook keeps track of tons of information and displays it on their websites and apps. Things like names, birthdays, status', etc. In order for us to write more complex programs like these, that do more than print text out onto the screen, we'll need to learn how to manage all of the information in our programs and use variables.
Variables are essentially containers which allow a program to store different pieces of information inside of them. Once the information is stored inside the variable, that information can then be accessed throughout the program simply by referring to the variable's name. Using variables is a great way to keep track of and organize your data. When creating variables, make sure to use descriptive names! For example, if we were creating a variable to hold someones age, using var age
is much better than var a
. This can save time trying to figure out what each variable is defining!
Let's make some variables in JS:
var phrase = "To be or not to be";
document.write(phrase);
var
is a special word in JS, which tells JS that a variable is being created. Now we can call the variable within the document.write();
command instead of having to type out the string. This can be very powerful and save programmers a ton of time! We can also change the variable after defining it originally:
var phrase = "To be or not to be";
document.write(phrase);
phrase = "Apple"
document.write(phrase);
To be or not to be
and apple
. We are not limited to only storing strings of text within a variable. We can also store numbers (whole numbers or decimals), boolean variables, undefined, and Null:
var name = "Nick"
var age = 25;
var gpa = 3.8;
var isMale = true;
var flaws = null;
var description = undefined;
document.write(`${name} is ${age} years old.`);
if(isMale = true){
document.write(`He has a ${gpa} GPA.`);
}
else{
document.write(`She has a ${gpa} GPA.`);
}
Nick is 25 years old.He has a 3.8 GPA.
null
and undefined
are different because when you use null
, you are saying that there is no value, but undefined
says that there is no value yet. You will probably not use null
or undefined
much as a developer, but they are still good to know/understand. The $
used above is called interpolation. This allows us to insert, or interpolate, variables into strings using template literals.
Notice that:
-
A template literal is wrapped by backticks ``` (this key is usually located on the top of your keyboard, left of the 1 key).
-
Inside the template literal, you’ll see a placeholder,
${myPet}
. The value ofmyPet
is inserted into the template literal. -
When we interpolate
I own a pet ${myPet}.
, the output we print is the string:'I own a pet armadillo.'
One of the biggest benefits to using template literals is the readability of the code. Using template literals, you can more easily tell what the new string will be. You also don't have to worry about escaping double quotes or single quotes.
Remember to use descriptive variable names! Think of a variable as a moving box. When you fill up the box it is common to write on the outside of the box what it contains. Use similar logic when it comes to naming variables.
Create a Variable: let
The let
keyword signlas that the variable can be reassigned a different value. Take a look at the example:
1 2 3 4 |
|
let
(and even var
) is that we can declare a variable without assigning the vairable a value. In such a case, the variable will be automatically initialized with a value of undefined
:1 2 3 4 |
|
Create a Variable: const
The const
keyword is short for the word constant, which means that it cannot be reassigned. Just like var
and let
, you can store any value in a const
variable (it also follows the same structure!). Take a look at the following example:
1 2 |
|
const
variable named myName
, which should never have to change. If you try to reassign a const
variable, you'll get a TypeError
. Constant variables must be assigned a value when declared. If you try to declare a const
variable without a value, you'll get a TypeError
.
If you're trying to decide between which keyword to use, let
or const
, think about whether you'll need to reassign the variable later on.
typeof
Operator
While writing code, it can be useful to keep track of the data types of the variables in your program. If you need to check the data type of a variable's value, you can use the typeof
operator.
The typeof
operator checks the value to its right and returns, or passes back, a string of the data type.
1 2 3 4 5 6 7 8 |
|
Strings
<<<<<<< HEAD Strings are any grouping of characters on your keyboard (letters, numbers, space, symbolsm etc.) surrounded by single quotes ' ... '
or double quotes " ... "
. Though we prefer single quotes. Some people like to think of string as a fancy word for text.
1 2 3 |
|
The following line will produced the string "concatenate
":
"con" + "cat" + "e" + "nate"
1 2 3 |
|
Booleans
Booleans have only two possible values - either true
or false
. It is helpful to think of booleans as on and off switches or as the answers to a "yes" or "no" question.
Here is one way to produce Boolean values:
1 2 3 4 |
|
1 2 |
|
Other similar operators are >=
(greater than or equal to), <=
(less than or equal to), ==
(equal to), and !=
(not equal to).
1 2 3 4 |
|
Numbers
Values of the number type are, unsurprisingly, numeric values. In a JavaScript program, they are written as follow:
44;
12.34;
Fractional numbers are simply written by using a dot (12.34
). For very big or very small numbers, you may also use scientific notation by adding an e (for exponent), followed by the exponent of the number:
2.998e8 // this is 2.998 x 10^8 = 299,800,000
Arithmetic Operators
Basic arithmetic operators often come in handy when programming.
An operator is a character that performs a task in our code. JavaScript has several built-in arithmetic operators, that allow us to perform mathematical calculations on numbers. These include the following operators and their corresponding symbols:
-
Add:
+
-
Subtract:
-
-
Multiply:
*
-
Divide:
/
-
Remainder:
%
The first four might work how you guess:
1 2 3 4 |
|
console.log()
the computer will evaluate the expression inside the parentheses and print that result to the console. If we wanted to print the characters 3+4
, we would wrap them in quotes and print them as a string. The remainder operator, sometimes known as modulo, returns the number that remains after the right-hand number divides into the left-hand number as many times as it can.
1 2 |
|
11 % 3
equals 2 because 3 fits into 11 three times, leaving two as the remainder. The Increment and Decrement Operator
Other mathematical assignment operators include the increment operator (++
) and decrement operator (--
).
The increment operator will increase the value of the variable by 1. The decrement operator will decrease the value of the variable by 1. For example:
1 2 3 |
|
1 2 3 |
|
+=
, -=
, *=
, /=
), the variable's value is updated and assigned as the new value of that variable. Properties
When you introduce a new piece of data into a JavaScript program, the browser saves it as an instance of the data type. Every string instance has a property called length
that stores the number of characters in that string. You can retrieve property information by appending the string with a period and the property name:
console.log("Hello".length); // prints 5
.
is another operator! We call it the dot operator. In the example above, the value saved to the length
property is retrieved from the instance of the string, "Hello"
. The program prints 5
to the console, because Hello
has five characters in it.
Methods
Remember that methods are actions we can perfrom. JavaScript provides a number of string methods. We call, or use, these methods by appending an instance with:
-
a period
.
(the dot operator) -
the name of the method
-
opening and closing parentheses
E.g. 'example string'.methodName();
.
Does that syntax look a little familiar? When we use console.log();
we're calling the .log()
method on the console
object. Let's see console.log()
and some real string methods in action!
1 2 |
|