JavaScript - Variable




JavaScript - Variable

A variable is a literal assigned to an identifier, so you can reference and use it later in the program. Variables in JavaScript do not have any type attached. Once you assign a specific literal type to a variable, you can later reassign the variable to host any other type, without type errors or any issue. This is why JavaScript is sometimes referred to as “untyped”. A variable must be declared before you can use it. There are 3 ways to do this, using var, let or const, and those 3 ways differ in how you can interact with the variable later on.

Variables are a fundamental part of many programming languages, and are among the first and most important concepts for novice coders to learn. There are a number of different properties of variables in JavaScript, as well as several rules which must be followed when naming them. In JavaScript, there are three keywords used to declare a variable — var, let, and const — and each one affects how the code will interpret the variable differently.

This tutorial will cover what variables are, how to declare and name them, and also take a closer look at the difference between var, let, and const. We will also review the effects of hoisting and the significance of global and local scope to a variable’s behavior.

A variable is a named container used for storing values. A piece of information that we might reference multiple times can be stored in a variable for later use or modification. In JavaScript, the value contained inside a variable can be any JavaScript data type, including a number, string, or object. Prior to the ECMAScript 2015 (ES6) language specification that today’s JavaScript is based on, there was only one way to declare a variable — using the var keyword. As a result, most older code and learning resources will only use var for variables. We’ll go over the differences between var, let, and const keywords in its own section below.

We can use var to demonstrate the concept of a variable itself. In the example below, we will declare a variable, and assign a value to it.

// Assign the string value Sammy to the username identifier
var username = "sammy_shark";

This statement consists of a few parts -

  • The declaration of a variable using the var keyword

  • The variable name (or identifier), username

  • The assignment operation, represented by the = syntax

  • The value being assigned, "sammy_shark"

Now we can use username in code. JavaScript will remember that username represents the string value sammy_shark.

// Check if variable is equal to value
if (username === "sammy_shark") {
  console.log(true);
}
true

As mentioned previously, variables can be used to represent any JavaScript data type. In this example, we’ll declare variables with string, number, object, Boolean, and null values.

// Assignment of various variables
var name = "Sammy";
var spartans = 300;
var kingdoms = [ "mammals", "birds", "fish" ];
var poem = { roses: "red", violets: "blue" };
var success = true;
var nothing = null;

Using console.log, we can see the value contained in a specific variable.

// Send spartans variable to the console
console.log(spartans);
300

Variables store data in memory which can later be accessed and modified. Variables can also be reassigned and given a new value. The simplified example below demonstrates how a password might be stored to a variable and then updated.

// Assign value to password variable
var password = "hunter2";

// Reassign variable value with a new value
password = "hunter3";

console.log(password);
'hunter3'

In an actual program, a password would most likely be securely stored in a database. This example, however, illustrates a situation in which we might need to update the value of a variable. The value of password was hunter2, but we reassigned it to hunter3 which is the value JavaScript recognizes from that point forward.

Naming Variables

Variable names are known as identifiers in JavaScript. We discussed several of the rules of naming identifiers in Understanding Syntax and Code Structure in JavaScript, summarized here, Variable names can consist only of letters (a-z), numbers (0-9), dollar sign symbols ($), and underscores (_) Variable names cannot contain any whitespace characters (tabs or spaces), Numbers cannot begin the name of any variable, There are several reserved keywords which cannot be used as the name of a variable, Variable names are case sensitive.

JavaScript also has the convention of using camel case (sometimes stylized as camelCase) in the names of functions and variables declared with var or let. This is the practice of writing the first word lowercase, and then capitalizing the first letter of every subsequent word with no spaces between them. Most variables that are not constants will follow this convention, with some exceptions. The names of variables that are constant, declared with the const keyword, are typically written in all uppercase.

This may seem like a lot of rules to learn, but it will very quickly become second nature to write valid and conventional variable names.

Variable Scope

Scope in JavaScript refers to the current context of code, which determines the ccessibility of variables to JavaScript. The two types of scope are local and global, Global variables are those declared outside of a block, Local variables are those declared inside of a block, In the example below, we will create a global variable.

// Initialize a global variable
var creature = "wolf";

We learned that variables can be reassigned. Using local scope, we can actually create new variables with the same name as a variable in an outer scope without changing or reassigning the original value. In the example below, we will create a global species variable. Within the function is a local variable with the same name. By sending them to the console, we can see how the variable’s value is different depending on the scope, and the original value is not changed.

// Initialize a global variable
var species = "human";

function transform() {
  // Initialize a local, function-scoped variable
  var species = "werewolf";
  console.log(species);
}

// Log the global and local variable
console.log(species);
transform();
console.log(species);
human
werewolf
human

Correct JavaScript variables

var x = 20;  
var _value="sonoo";  

Incorrect JavaScript variables

var  123=30;  
var *aa=320;  

Example of JavaScript variable

Let’s see a simple example of JavaScript variable.

<html>
<body>
<script>  
var x = 20;  
var y = 40;  
var z=x+y;  
document.write(z);  
</script>  
</body>
</html>

Output of the above example

80