JavaScript: Many Variables in One Statement

Declaring multiple variables in one statement is very much possible in javascript it is quite easy and makes the code look clean too.

Example: Declaring a Variable

Let's see a few examples of declaring a variable in a statement:

var name = 'Neo', age = 21, city = 'NewYork' //3 variables declared and assigned value 
console.log(name,age,city)

Output:

Neo 21 NewYork
  • So here we basically stored some values inside the name, age, and city with the keyword var.
  • It can be accessed without any flaw.

Example: Based on Object

Let's see another example based on objects:

let titan = {titanName: 'Attack Titan', age: 30, realName:'Reiner Braun' }
let {titanName,age,realName}=titan;

console.log(titanName)
console.log(realName)
console.log(age)

Output:

Attack Titan
Reiner Braun
30
  • This is another way of storing values in variables with objects assigned.
  • And we are letting that objects know that it is equal to the variable name 'titan'.
  • After that, it can be accessed normally like any other value from a variable.

So check out the code and play around with it in your own way.

Wed, 09/15/2021 - 10:49

Authored by

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.
Tags