JavaScript Variables
JavaScript Variables: let, const, and var
Section titled “JavaScript Variables: let, const, and var”JavaScript Variables
Section titled “JavaScript Variables”JavaScript variables are named containers for storing data values. Think of them as labels for information your program needs to remember and work with.
In this example, x, y, and sum are variables:
const x = 5;const y = 6;const sum = x + y; // sum will store the value 11From the example above:
xstores the value 5.ystores the value 6.sumstores the result ofx + y, which is 11.
Declaring Variables: let, const, and var
Section titled “Declaring Variables: let, const, and var”In modern JavaScript (ES6 and later), variables are typically declared using let and const. The older keyword var also exists but has different scoping rules and is generally avoided in new code.
let: Declares a block-scoped variable. The value of aletvariable can be reassigned.const: Declares a block-scoped constant. Its value cannot be reassigned after initialization. For objects and arrays,constmeans the reference to the object/array cannot change, but the contents of the object/array can still be modified.var: Declares a function-scoped or globally-scoped variable (older syntax). It can be reassigned and re-declared.
Creating (declaring) a variable in JavaScript:
let carName; // Declares a variable named carName (value is undefined initially)carName = "Volvo"; // Assigns the string "Volvo" to carName
const year = 2024; // Declares a constant and initializes it// year = 2025; // This would cause an error because 'year' is a constantIt’s good practice to declare variables before they are used and initialize const variables at the time of declaration.
Variable Scope
Section titled “Variable Scope”Scope determines the accessibility (visibility) of variables.
- Block Scope (
letandconst): Variables declared withletandconstare only accessible within the block of code (defined by{...}) where they are declared. This includes loops, if statements, and function blocks. - Function Scope (
var): Variables declared withvarare accessible throughout the function in which they are declared, regardless of block structure. - Global Scope: Variables declared outside any function or block are global and accessible from anywhere in your script.
Example of block scope:
function testScope() { if (true) { let blockScopedVar = "I am block-scoped"; const blockScopedConst = "Me too!"; var functionScopedVar = "I am function-scoped"; console.log(blockScopedVar); // Accessible } // console.log(blockScopedVar); // Error: blockScopedVar is not defined here // console.log(blockScopedConst); // Error: blockScopedConst is not defined here console.log(functionScopedVar); // Accessible}testScope();Using let and const helps prevent bugs related to variable hoisting and unintended global variables that were common with var.
JavaScript Identifiers (Variable Names)
Section titled “JavaScript Identifiers (Variable Names)”All JavaScript variables must be identified with unique names, called identifiers.
Rules for constructing variable names:
- Names can contain letters, digits, underscores (
_), and dollar signs ($). - Names must begin with a letter, a dollar sign (
$), or an underscore (_). (Conventionally, start with a letter). - Names are case sensitive (
myVariableandmyvariableare different). - Reserved keywords (like
let,const,function,if) cannot be used as variable names.
Use descriptive and meaningful names (e.g., userName, totalAmount) to make your code more readable. CamelCase (userName) is the standard convention.
The Assignment Operator (=)
Section titled “The Assignment Operator (=)”In JavaScript, the equal sign (=) is an assignment operator, not an “equal to” operator (for equality, use == or ===).
It assigns the value on its right to the variable on its left.
let x = 10; // Assigns 10 to xx = x + 5; // Assigns the value of (x + 5) back to x. Now x is 15.JavaScript Data Types
Section titled “JavaScript Data Types”JavaScript variables can hold different types of data:
- String: Textual data, e.g.,
"Hello",'JavaScript'. (Enclosed in quotes or backticks). - Number: Numeric data, e.g.,
100,3.14,2.5e5(scientific notation). JavaScript has one number type for both integers and floating-point numbers. - Boolean: Logical values,
trueorfalse. - Object: A collection of key-value pairs, e.g.,
{ name: "John", age: 30 }. Arrays and Functions are also types of objects. - Array: An ordered list of values, e.g.,
[1, 2, "apple"]. - null: Represents the intentional absence of any object value.
- undefined: Indicates that a variable has been declared but not yet assigned a value.
- Symbol (ES6): A unique and immutable primitive value, often used as object property keys.
- BigInt (ES2020): For integers of arbitrary length.
JavaScript is dynamically typed, meaning you don’t have to declare the type of a variable. The type is determined automatically at runtime.
let pi = 3.14; // pi is a Numberlet person = "John Doe"; // person is a Stringlet isHappy = true; // isHappy is a BooleanDeclaring Multiple Variables
Section titled “Declaring Multiple Variables”You can declare multiple variables in one statement, separated by commas. However, it’s often clearer to declare each variable on its own line.
// Common way:let name = "John Doe";let age = 30;let city = "New York";
// Also possible (less common for `let` and `const` due to block scoping benefits of separate lines):let user = "Jane", role = "Admin", experience = 5;Value of undefined
Section titled “Value of undefined”A variable declared without an assigned value will have the value undefined.
let country;console.log(country); // Output: undefinedRe-Declaring Variables
Section titled “Re-Declaring Variables”let and const: Variables declared with let or const cannot be re-declared within the same scope. Doing so will result in a SyntaxError.
let myVar = "initial";// let myVar = "new"; // Error: Identifier 'myVar' has already been declared
const myConst = 10;// const myConst = 20; // Error: Identifier 'myConst' has already been declaredvar (Older Syntax): Variables declared with var can be re-declared in the same scope without error. The re-declaration is effectively ignored if it doesn’t also assign a new value; if it does, the variable takes the new value.
var oldVar = "Volvo";var oldVar; // No error, oldVar is still "Volvo"console.log(oldVar); // Output: "Volvo"
var oldVar = "Saab"; // Re-assignment along with re-declarationconsole.log(oldVar); // Output: "Saab"This re-declaration behavior of var can lead to bugs, which is one reason let and const are preferred.
JavaScript Arithmetic and Type Coercion
Section titled “JavaScript Arithmetic and Type Coercion”You can perform arithmetic operations with JavaScript variables using operators like +, -, *, /.
const x = 5 + 2 + 3; // x will be 10JavaScript performs type coercion when operators are used with mixed types. The + operator is special: it performs addition for numbers and concatenation for strings.
const strNum = "5" + 2 + 3; // Result: "523" (String concatenation)const numStr = 2 + 3 + "5"; // Result: "55" (Addition then concatenation)
console.log("The year is " + 2024); // Result: "The year is 2024"If you use the + operator and one of the operands is a string, JavaScript will convert the other operand(s) to strings and perform concatenation. Be mindful of this behavior. |
|---|