Variables in JavaScript

January 29, 2025 1 Comment » Hits : 300





What is Variable ?

  1. JavaScript Variable is a container that can store value or expression.
  2. We can assign value/expression to variable.
  3. Variable can hold only one value at a time.

How to declare Variable in JavaScript ?

var variable_name;

Explanation :

  • We can declare variable using “var” keyword.
  • We can declare one or more variable at a time.
  • We can initialize variable at the time of declaration.
  • We can declare “n number” of variables as per requirement.

Different methods of declaring JavaScript variables

  1. Declaring One JavaScript variable
  2. Declaring Multiple JavaScript variable.
  3. Declaring and Assigning One JavaScript Variable.
  4. Declaring and Assigning Multiple JavaScript Variables.
// Declaring one JavaScript Variable
var sub1;
// Declaring Multiple JavaScript Variables
var sub1, sub2;
// Declaring and Assigning one JavaScript Variable
var sub1 = 78;
// Declaring and Assigning n JavaScript Variable
var sub1 = 78 , sub2 = 90;

Rules for Creating JavaScript Variables :

  1. Variable name contain any Letter of the alphabet, Digits (0-9), and the Underscore character.
  2. Spaces,Punctuation marks and Special Symbols are not allowed.
  3. The first character of a variable name cannot be a Digit.
  4. JavaScript variable’s names are Case-Sensitive.
  5. For example sub1 and Sub1 are two different variables.

Incoming search terms:

  • Tanghus

    Hi

    I’ve been searching for a way to assign values to multiple values from an array. This is very easy to achieve on Python where you can do something like:

    fam, giv, add, pre, suf = ‘Swanson;Graham;Rudolf;Dr.;MD’.split(‘;’)

    But I haven’t found a solution in Javascript.
    I’ve tried:

    var [fam, giv, add, pre, suf] = ‘Swanson;Graham;Rudolf;Dr.;MD’.split(‘;’);

    Which works in Firefox but not in Chrome

    var (fam, giv, add, pre, suf) = ‘Swanson;Graham;Rudolf;Dr.;MD’.split(‘;’);

    Which doesn’t work in Firefox.

    var fam, giv, add, pre, suf;
    (fam, giv, add, pre, suf) = ‘Swanson;Graham;Rudolf;Dr.;MD’.split(‘;’);

    or

    var fam, giv, add, pre, suf;
    fam, giv, add, pre, suf = ‘Swanson;Graham;Rudolf;Dr.;MD’.split(‘;’);

    But none if them works. Is it really not possible to variable assignment like that in Javascript?