Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How can I declare and define multiple variables in one statement with JavaScript?
In JavaScript, you can declare and define multiple variables in a single statement by separating them with commas. This approach works with var, let, and const keywords.
Syntax
var variable1 = value1,
variable2 = value2,
variable3 = value3;
// Or with let/const
let variable1 = value1,
variable2 = value2,
variable3 = value3;
Example: Using var
var firstName = "My First Name is David",
lastName = "My Last Name is Miller",
place = "I live in AUS";
console.log(firstName);
console.log(lastName);
console.log(place);
My First Name is David My Last Name is Miller I live in AUS
Example: Using let and const
let name = "John",
age = 25,
isStudent = true;
const PI = 3.14159,
GRAVITY = 9.8,
MAX_SIZE = 100;
console.log(`Name: ${name}, Age: ${age}, Student: ${isStudent}`);
console.log(`PI: ${PI}, Gravity: ${GRAVITY}, Max Size: ${MAX_SIZE}`);
Name: John, Age: 25, Student: true PI: 3.14159, Gravity: 9.8, Max Size: 100
Mixed Declarations
You can also declare some variables without initial values:
let x = 10,
y, // undefined
z = "hello",
w; // undefined
console.log("x:", x);
console.log("y:", y);
console.log("z:", z);
console.log("w:", w);
x: 10 y: undefined z: hello w: undefined
Key Points
- Use commas to separate multiple variable declarations
- Works with
var,let, andconst - Variables can have different data types in the same statement
- Some variables can be left undefined while others are initialized
Conclusion
Multiple variable declarations in one statement help write cleaner, more concise code. Use this syntax when declaring related variables together, but ensure readability is maintained.
Advertisements
