Variables, Comments, and Data Types
Variables
In programming, a variable is like a bucket where we can store values.
In JavaScript, variables can be defined using the let keyword and the = assignment operator. Ex:
let experimentName = 'Stroop';
In the above code, the variable we created is called experimentName
and we set it to the String 'Stroop'
.
Once a variable is defined, it can be used and updated throughout your code. Here are some examples:
// Define a variable called `experimentName` and set its value to 'Stroop'
let experimentName = 'Stroop';
// Output the experimentName to the console
console.log(experimentName);
// Output the experimentName concatenated (i.e joined) with some welcome text
// The + operator is used to concatenate together strings and variables
console.log('Welcome to the ' + experimentName + ' experiment.');
// Update the experimentName variable
experimentName = 'Go/No-Go';
// Output the number of characters in the experimentName
console.log(experimentName.length);
Output from the above code:
Stroop
Welcome to the Stroop experiment.
18
Naming variables
Here are conventions/rules to follow when naming variables in JavaScript:
- Descriptive: Variable names should be descriptive and convey the purpose of the variable. This helps make code more readable and maintainable.
- Valid Characters: Variables names can contain letters (both uppercase and lowercase), digits, underscores (_), and dollar signs ($). They can not start with a digit.
- No Spaces: Variable names cannot contain spaces. In this course we will use a lowerCamelCase convention in place of spaces when naming variables. lowerCamelCase style means that the first word is in lowercase, and every new word starts with a capital letter (ref).
- Reserved Keywords: variable names cannot be the same as JavaScript keywords or reserved words. For example, you cannot name a variable if, for, function, etc. Sometimes you might unknowingly use a reserved word, but if you do you’ll get an error so just be on the lookout for that.
Comments
The above code introduces Comments. Comments are notes that we can add to our code that will be ignored by the JavaScript interpreter. One way to define comments in JavaScript is by prefixing them with two forward slash characters:
// Define a variable called `experimentName` and set its value to 'Lexical Decision Task'
let experimentName = 'Lexical Decision Task';
In the above examples, we’re using a comment to explicitly state what the line of code is doing which can be useful for teaching/learning purposes. As you get more comfortable with programming, though, you won’t have to be as explicit in your comments and you should get in the practice of only commenting what is not obvious by the code itself.
Writing clear comments that help organize and clarify code (to yourself and collaborators) is an important programming skill, so it’s something we’ll be practicing.
Other uses for comments
Beside leaving notes to yourself and collaborators to clarify code, comments might be used to disable lines of code that you wish the JavaScript interpreter to ignore. We refer to this as “commenting out” code.
For example, below is some JavaScript code where we’ve defined a few different sets of sample scores. Notice how only the first line is “active”, because the two that follow are “commented out”, effectively disabling them since they will be ignored by the JavaScript interpreter:
let sampleScores = [75, 90, 91, 92, 45];
//let sampleScores = [75, 90, 91, 99, 45];
//let sampleScores = [64, 89, 71, 82, 100];
let highScore = Math.max(...sampleScores);
console.log(highScore); // 92
As you spend more time with code, you’ll start to find many situations where the ability to “comment out” lines of code is useful, and it’s something you’ll see us using throughout this course.
Another context in which we’ll use comments, especially in these note sets, is to indicate the results that will be produced by JavaScript from a line (or lines) of code.
For example, above we wrote:
console.log(highScore); // 92
Here the comment // 92
is just indicating that we expect this line to produce the results 92.
Data types - String
let experimentName = 'Stroop';
// JavaScript's built-in typeof operator can be used to inspect the data type of a value
console.log(typeof experimentName); // string
In the above code, we set a variable to a String, 'Stroop'. A String is a data type used in many programming languages, and it consists of a sequence of mixed characters (letters, numbers, special symbols). In JavaScript, a String can be defined using single or double quotes, e.g:
let experimentNameA = 'Stroop';
let experimentNameB = "Go/No-Go";
You can also create single or multi-line Strings using backticks. This is useful for longer Strings where line breaks can help improve readability.
let welcomeMessage = `
Welcome to the experiment.
Please make sure your volume is turned up.
Press SPACE to begin
`;
One way to join variables and strings is to use the +
concatenation operator:
alert('Welcome to the ' + experimentName + ' experiment!');
Alternatively, if you’re using backticks, you can use use string interpolation, which is a programming technique that replaces placeholders in a String with their corresponding values. The syntax ${...}
is used for string interpolation. Example:
alert(`Welcome to the ${experimentName} experiment!`);
Data types - Number
For numerical content, JavaScript has the Number data type which can be set to integers (whole) or floating point (decimal) numbers.
let age = 42; // Example of a integer Number
console.log(typeof age); // number
let averageAge = 34.5; // Example of a floating point Number
console.log(typeof averageAge); // number
Data types - Boolean
Another commonly encountered data type in programming is a Boolean value, indicated as either true or false.
let correct = true;
console.log(typeof correct); // boolean
console.log(correct); // true
correct = false;
console.log(typeof correct); // boolean
console.log(correct); // false
Boolean data types are often used as part of Boolean expressions which compare two values using operators such as > greater than, < less than, and == equal to. For example:
let age = 25;
let adult = age > 18;
console.log(adult); // true
console.log(typeof adult); // boolean
In the above code the Boolean expression is age > 18 and it evaluates to the Boolean value of true.
Boolean expressions come in handy when constructing conditionals which allow you to selectively execute different lines of code based on certain conditions. We’ll discuss conditionals and dig deeper into boolean values and expressions next week.
For now, just remember that the Boolean data type is either true or false.
Why data types matter
Understanding the data type assigned to our values by JavaScript “behind the scenes” is important because there are certain operations available to different data types.
For example, with Strings we can use JavaScript’s charAt method to extract a specific character from a String using an index position:
let experimentName = 'Stroop';
console.log(experimentName.charAt(0)); // S
If we tried to use that same method with a Number, however, we’d get an error:
let age = 55;
console.log(age.charAt(0)); // Produces the error "TypeError: age.charAt is not a function"
There are other instances where data types matter, so it’s important to have a baseline understanding of them when working with values.
Observe how in the above example using charAt, the starting position of the string is 0, not 1:
let experimentName = 'Stroop';
console.log(experimentName.charAt(0)); // S
In programming, it’s very common to start counts at 0.
Compound data types
The data types of String and Number discussed above are examples of scalar data types, which means they hold single values. In addition to scalar data types, JavaScript has compound data types that can contain a collection of values.
For example, there is the Array data type that can store multiple elements, separated by commas within square brackets. Examples:
// An Array of Numbers
let scores = [75.5, 91, 91.6, 92.3, 45.5];
// An Array of Strings
let words = ['pear', 'mouse', 'red', 'igloo'];
// An Array of mixed data types, including a sub-array
let misc = [90, 'green', 45.5, ['a', 'b', 'c']];
There are also Objects which are collections of key-value pairs. Example:
let experiment = {
name: 'Stroop',
colors: ['red', 'green', 'blue'],
trialCount: 10
};
We’ll dig deeper into compound data types in future content as they're a very useful tool within programming.