Fall 2024 - P3
3.1.3 Javascript Variables
Let's learn how variables work in Javascript
Variables
Variables are containers that are used to store data in programming languages. In JavaScript there are 3 ways to declare a variable.
- var
- let
- const
var is an outdated way of declaring variables, and so we will disregard teaching it as you will only use let and const.
Const: Use when the variable shouldn’t be reassigned. Let: Use when the variable’s value may change over time.
%%js
//Pi and user variables don't change
const pi = 3.14159265358979;
const user = "Spencer";
//Count variable is being updated
let count = 0;
for (let i = 0; i < 10; i++) {
console.log(i)
}
Assignment Operator
JavaScript’s assignment operator is equal (=) which assigns the value of the thing to the right to equal the variable to the left. The equal sign shouldn’t be confused as equality, as it’s exclusively reserved for assignment in programming languages.
== is used to test equality between two things
%%js
let x = 5
let y = 3
let z = 2
Variable Naming
There are some limitations when it comes to naming variables in JavaScript
- The name can only contain letters, digits, or the symbols $ and _.
- The variable musn’t start with a digit
Examples of valid & invalid variable names:
%%js
//Valid variable names
let color;
let _favoriteColor;
//Invalid variable names
let 123badVariable;
let my-age;
Naming Conventions
When naming variables, it’s an important skill to make clear, concise, and meaningful variable names. This will help your peers and your future self.
Here are some guidelines to follow:
- Use clear, human-readable names like
userName
orshoppingCart
. - Avoid using cryptic abbreviations or single-letter names like
a
,b
, orc
, unless it’s absolutely clear what they mean. - Strive for names that are both descriptive and to the point. Generic names like
data
orvalue
don’t provide much insight. - Stick to consistent terminology. If you refer to someone on your site as a “user,” stay consistent with terms like
currentUser
ornewUser
instead of changing it up with something likecurrentVisitor
.
Here are some examples:
// BAD: unclear and too generic
let a = 30;
let data = "John Doe";
let value = true;
// GOOD: descriptive and clear
let userAge = 30;
let userName = "John Doe";
let isUserLoggedIn = true;
// BAD: abbreviations and short names
let usrNm = "Jane";
let c = 100;
let t = new Date();
// GOOD: human-readable and consistent
let customerName = "Jane";
let cartTotal = 100;
let currentDate = new Date();
// BAD: inconsistent terminology
let visitorId = 123;
let currentVisitor = "John";
let siteMember = "Jane";
// GOOD: consistent and concise
let userId = 123;
let currentUser = "John";
let newUser = "Jane";
Further Study on Coding Conventions
To deepen your understanding of variables and coding conventions, you can explore the following resource:
Click the button below to directly access the tutorial: