JavaScript Variables and Expressions
What are the Variables
- Variables are used to store and manage data in JavaScript.
- They act as containers for values, and their contents can change during program execution.
- These data values can be numbers, text, booleans, or more complex data types such as objects, arrays, etc.
Declaring Variables in JavaScript
- Declare variables using var, let, or const.
- var variables are function-scoped, which means that they can be accessed from anywhere within the function in which they are declared.
- Historically, this was the primary way to declare variables, but it has some issues (like hoisting and global scope). We recommend avoiding it.
- let: Introduced later, let is the preferred way to declare variables. It provides block-level scoping and avoids the pitfalls of var.
- const: Used for constants, const declares a variable that cannot be changed after its initial assignment.
Let's declare a variable using let
let message; // Declaring a variable without assigning a value
In the above example, message is a variable, and its default value is undefined.
Once declared, we can assign a value to a variable using the = operator.
let greeting;
greeting = "Hello, JavaScript!"; // Assigning a string value
Alternatively, we can declare and initialize a variable in a single line
let name = "John"; // Assigned a string value
let age = 30; // Assigned a numeric value
let isStudent = true; // Assigned a boolean value
You can declare multiple variables in a single line.
let firstName = "John", lastName = "Doe", score = 85;
You can copy the value of one variable to another.
let originalValue = 100;
let copiedValue = originalValue;
JavaScript allows multiple spaces and line breaks when declaring variables.
let city = "New York",
population = 8_500_000;
Naming Conventions
- Variable names must begin with a letter, underscore (_), or dollar sign ($).
- They cannot start with a digit (0-9).
- Variable names are case-sensitive (e.g., msg, MSG, Msg, and mSg are different variables).
- Avoid using reserved keywords like var, function, or return.
Valid Variable Names
myVariable
_myVariable
$myVariable
ageInDays
productPrice
totalNumberOfCustomers
Invalid Variable Names
1myVariable
my-variable
my variable
const
function
var
Dynamic Typing
JavaScript is loosely typed, meaning you don't need to specify a variable's data type explicitly. It adapts based on the assigned value. That means it can hold different types of values.
let numberVar = 42; // Number
let stringVar = "Hello"; // String
let boolVar = true; // Boolean
let arrayVar = [1, 2, 3]; // Array
let objVar = { key: "value" }; // Object
Updating Variables
- Use the assignment operator (=) to update a variable's value.
let count = 5;
count = count + 1; // Increment by 1 now count value is 6
Expressions
- Expressions are combinations of values, operators, and variables.
- They are used to perform operations and produce results.
let total = 2 * (5 + 3); // total equals 16
String Concatenation
- Strings can be concatenated using the + operator.
let firstName = "Jack";
let lastName = "Salvatore";
let fullName = firstName + " " + lastName; // fullName equals "Jack Salvatore"
Template Literals
- Template literals (enclosed in backticks) allow for easy string interpolation.
let name = "Alice";
let greeting = `Hello, ${name}!`; // greeting equals "Hello, Alice!"
A Complete JavaScript Variables Examples
// Declare a variable and assign it a value
var myName = "Jack Salvatore";
// Declare a variable without assigning it a value
let myAge;
// Assign a value to the variable `myAge`
myAge = 30;
// Declare a constant and assign it a value
const MY_FAVORITE_NUMBER = 7;
// Use variables in an expression
var myTotal = myAge + MY_FAVORITE_NUMBER;
// Use an expression in a variable assignment
let myAverage = (myAge + MY_FAVORITE_NUMBER) / 2;
// Log the values of the variables to the console
console.log(myName); // Outputs "Jack Salvatore"
console.log(myAge); // Outputs 30
console.log(MY_FAVORITE_NUMBER); // Outputs 7
console.log(myTotal); // Outputs 37