Basics of JavaScript
Variables
Variables are containers that store values. You start by declaring a variable with the var (less recommended, dive deeper for the explanation) or the let keyword, followed by the name you give to the variable:
let myVariable;
Note: A semicolon at the end of a line indicates where a statement ends. It is only required when you need to separate statements on a single line.
Note: You can name a variable nearly anything, but there are some restrictions. If you are unsure, you can check your variable name to see if it's valid.
Note: JavaScript is case sensitive. This means myVariable is not the same as myvariable. If you have problems in your code, check the case.
After declaring a variable, you can give it a value:
myVariable = 'Bob';
Also, you can do both these operations on the same line:
let myVariable = 'Bob';
You retrieve the value by calling the variable name:
myVariable;
After assigning a value to a variable, you can change it later in the code:
let myVariable = 'Bob';
myVariable = 'Steve';
Note that variables may hold values that have different data types:
Variable |
Explanation |
Example |
This is a sequence of text known as a string. To signify that the value is a string, enclose it in single quote marks. |
let myVariable = 'Bob'; |
|
This is a number. Numbers don't have quotes around them. |
let myVariable = 10; |
|
This is a True/False value. The words true and false are special keywords that don't need quote marks. |
let myVariable = true; |
|
This is a structure that allows you to store multiple values in a single reference. |
let myVariable = [1,'Bob','Steve',10]; |
|
|
Refer to each member of the array like this: |
|
|
myVariable[0], myVariable[1], etc. |
|
This can be anything. Everything in JavaScript is an object and can be stored in a variable. Keep this in mind as you learn. |
let myVariable = document.querySelector('h1'); |
|
|
So why do we need variables? Variables are necessary to do anything interesting in programming. If values couldn't change, then you couldn't do anything dynamic, like personalize a greeting message or change an image displayed in an image gallery.
Comments
Comments are snippets of text that can be added along with code. The browser ignores text marked as comments. You can write comments in JavaScript as shown below:
/*
Everything in between is a comment.
*/
If your comment contains no line breaks, it's an option to put it behind two slashes like this:
// This is a comment
Operators
An operator is a mathematical symbol which produces a result based on two values (or variables). In the following table you can see some of the simplest operators, along with some examples to try in the JavaScript console.
