Basic JavaSxcript Syntax

Variables

What are variables?

Variables can be thought of as a 'container' that stores, or holds, information. We use variables in calculations to hold values that can be changed.

Variables must be declared before they can be used. This means we name the variable and assign it a storage space in memory, so that we can reference it later. This tells JavaScript that we want to set aside a chunk of space in the computer's memory for our program to use. In JavaScript we use the following format to create a variable and assign a value to it:

let variable_name = value_you_want_to_store;

What are Var and Const?

These are keywords that can be used to declare variables. Var is the old way of creating a variable (we generally use the 'let' keyword now). The let keyword allows a variable to be reassigned a different value. Const is used when you want to declare a variable whose value can't change, i.e. the variable stores a constant value and cannot be reassigned. Const is a great option when you want to ensure a variable doesn't accidentally get reassigned a different value, for example:

const variable_name = permanent_value_you_want_to_store;

Naming variables

You can name a variable anything you like, as long as the name:

  1. Contains only letters, numbers and underscores. All other characters are prohibited from use in variable names, including spaces. For example, My name would not be an acceptable variable name, whereas My_Name would be acceptable.
  2. Starts with a letter.
  3. Is not a reserved word. In JavaScript, certain words are reserved. For example, you would not be able to name a variable var, console or log because these are reserved words.

If you follow these rules, you can call your variables whatever you want. Note that it is good practice to give your variables meaningful names, so that your code is easily readable and understandable.




Practice what you've learned!

Question 1:

How do you declare a variable that may be reassigned later?


Question 2:

Which of these variable names is NOT correct?