JavaScript Variables



JavaScript variables:

JavaScript variables are containers for storing data values. We can declare a variable with three keywords such as let, var, and const.  JavaScript can store and label data in memory.


Example:

var man = 'hasan';
let age = 20;
const boy = "adam"; 


Here,
man, age, and boy are the names of the variables. 
= is the assignment operator


JavaScript identifiers / naming of JavaScript Variables : 

To identify javaScript variables with a unique name is called JavaScript identifiers. Identifiers can be short names (like x and y) and can be descriptive names(like age, address, totalPrice, etc).



General rules for constructing names for variables:

  • Names can contain letters, underscore, or dollar signs.
  • Variable names cannot start with numbers.
  • Names can also begin with $ or _ (not recommended).
  • Names are case sensitive(y and Y are not the same).
  • Reserved words(JavaScript keyword) cannot be used as names.


Additional information: 

Variable names or identifiers can also be a camelcase letter. 


Camelcase(the standard form of naming in JavaScript): 

There are two types of camelcase letters. For example…

  • UpperCamelCase: The first letter of each of the multiple words will be capitalized e.g; TotalPrice, FirstYearCal.
  • lowerUpperCase: The first letter of the first word in multiple words will be lowercase and the first letters of the remaining word will be capitalized e.g; totalPrice, firstYearCal.


PascalCase : 

Here PascalCase and UpperCamelCase are the same.



Declare a variable:

We can declare a variable and assign a value. We can also reassign a new value. Here, if we declare a variable without assigning the variable value, then the variable will be automatically initialized with a value of undefined.




Create a variable with the const keyword:

Like the keyword let and var, we can declare a variable with the keyword const and assign a value to it. But we cannot reassign a value to a variable declared with the const keyword. If we reassign a value to a variable declared with the const keyword it will return a TypeError message.

Again if we don’t assign any value to a variable declared with a const keyword, it will return a SyntaxError message.


let versus var versus const variable:

As we can declare a variable by three keywords such as let or var or const keywords. Now, I will discuss these deeply. 


Function level variable (with var keyword):

When we declare a variable within the function with the var keyword called function level variable because we can call or use or reassign this variable from anywhere in the function.


Example:

function age() {
  for(var i = 0; i < 5; i++){
    console.log(i);
    }
    console.log(i);
}
age();

Here we have used the variable "i" outside of the "for" loop. For this, we call the variable a function level variable.


Block-level variables : 

Block-level variables are variables that exist within the context of block statements (such as if or within curly braces) and then are destroyed completely after the statement is finished executing.





There are two types of block-level variables as 

  • let
  • const


let:

The variable with the let keyword is a block-level variable. The value of this variable can be changed through reassignment, and it can be redeclared within the block statement.


function letTest {
 let x = 1;
if(true){
    let x = 2 // different variable
    console.log(x) // output 2
    }
console.log(x); // output 1
}
letTest();


const (the short form of constant):

The variable with the const keyword is also a block-level variable. The value of a constant variable can’t be changed through reassignment, and it can’t be redeclared.


function letTest { let x = 1; if(true){ const x = 2 // different variable console.log(x) // output 2 x = 6; // this with generate a an error because // const variable can't be redeclared console.log(x); } } if(true){ const x = 2 // different variable console.log(x) // output 2 x = 6; // this with generate a an error because // const variable can't be redeclared console.log(x); } } if(true){ const x = 2 // different variable console.log(x) // output 2 x = 6; // this with generate a an error because // const variable can't be redeclared console.log(x); } } letTest();


Mathematical assignment operators and variables:

We can use variables and math operators to calculate a new value and assign them to a new variable.

Let’s look at the following example…


let x = 4;
x = x + 1;


Here, we have declared a variable named x with the number 4 assigned to it. On the following line, the value increases from 4 to 5.

Notice attentively that we have used the x variable on the left and right side of the assignment operators (=). The variable x is used here twice, which is redundant and confusing. This is also a problem. 

We can solve this problem. JavaScript has some built-in mathematical assignment operators that make it easy to calculate a new value and assign it to the same variable without writing the variable twice.


let x = 4;
x += 2; // equivalent to x = x + 2
        // output 6

let x = 4;
z -= 2; // equivalent to z = z - 2
       // output 2

let x = 4;
x *= 2; // equivalent to x = x * 2;
       // output 8

let x = 4;
x++;  // equivalent to x = x + 1;
      // output 5;

let x = 4; 
x--; // equivalent to x = x - 1;
     // output 3

The above three examples are used to calculate a new variable and assign these to the same variable.
And the last two examples are used for the increment and decrement of the value of the variable.





String interpolation:

Inserting the data to a variable and using the variable to a string is called string interpolation. Usually, we use + as an addition operator but in JavaScript, we can use this to interpolate a string variable into a string.
We can also combine strings with +
;


let x = "New York";
console.log('I am living in' + x + ', USA.';
// Output: I am living in New York, USA.


Here in the first line, we saved the value “New York” to the variable x. In the second line we have combined three strings “I am living in”, the value saved to the variable x, and “. "


String interpolation(newest method):

In the newest version of JavaScript(ES6), we can easily insert variables into a string. For this, we can use backticks (located just left side of 1 of the keyboard) instead of using quotes around the string. We can wrap the variable with ${variable name} followed by a sentence. Here no need for a + operator. This will be transparent with the following example…”


let myAnimal = "Tiger";
console.log(`I love animal like ${myAnimal}.`);
Ouput: I love animal like Tiger.


In the example above, backticks(``) wrap the entire string where the variable named myAnimal is inserted into the string with ${};



Undefined variable:

When we declare any variable but don’t assign any value to it. In such a case, the variable will be initialized with a value of undefined. Here JavaScript creates a space for this variable and sets it to undefined.

Example:


let notDefined;
console.log(notDefined);

Here notDefined is an undefined variable.


Post a Comment

Previous Post Next Post