Site icon Eval

JavaScript Variables: JavaScript Tutorial & Demo 6

JavaScript Tutorial & Demo 6 JavaScript Variables

Variables: This article will show you how to utilize JavaScript variables to store values in application.

What are “Variables”?

Variable refers to something that can change or differ. Variables are used to store data such as strings of text, integers, etc. The variables’ data or values can be set, modified, and retrieved as needed. Variables, in general, are symbolic names for values.

In simple words , a JavaScript variable is just the name of a storage place where data or expressions are stored. Always give your variables meaningful names, and it will assist you and others in better understanding the code.

Variable Declaration in JavaScript

Variable initialization is the process of storing a value in a variable. Variable initialization can be performed at the time of variable declaration or later when the variable is required. In JavaScript, there are four ways to declare variables.

Demo Syntax 1: Using ‘var’

var <variable-name>;

OR

var <variable-name> = <value>;

Demo Example 1

var x;

Demo Example 2

Var y = 12;

Variables defined using the var keyword are x, y, and z in the preceding instances.

Demo Syntax 2: Using ‘let’

let <variable-name>;

OR

let <variable-name> = <value>;

Demo Example 1

let x;
let y;

Demo Example 2

let z = x+y;

Variables x, y, and z are defined with the let keyword in the preceding instances.

Demo Syntax 3: Using ‘const’

const <variable-name>;

OR

let <variable-name> = <value>;

Demo Example 1

const x;
const y;

Demo Example 2

const z = x+y;

The variables x, y, and z in the preceding examples are specified with the const keyword.

Demo Syntax 4: Using nothing or undeclared

<variable-name>;

OR

<variable-name> = <value>;

Demo Example 1

x;
y;

Demo Example 2

z = x+y;

x, y, and z are undeclared variables in the preceding instances.

What to use for variable declaration: var, let, const or undeclared

Undeclared variable

This happens when you try to access a variable that hasn’t been declared using var, let, or const. Declaring a variable without the var keyword is not recommended since it may mistakenly overwrite an existing global variable.

JavaScript Identifiers

Variables, functions, and other objects in JavaScript are given names called identifiers. Though you may name identifiers anyway you like, giving them descriptive names is a good idea. In other terms, an identifier is a code sequence that identifies a variable, function, or attribute.

The difference between an identifier and a string is that a string is a data, but an identifier is part of the code. There is no mechanism to transform identifiers to strings in JavaScript; however, it is sometimes feasible to parse texts into identifiers. Identifiers in JavaScript are case-sensitive and can contain Unicode characters, $, _, and digits (0-9), but they cannot begin with a digit.

General guidelines for creating variable names (Identifiers)

JavaScript Reserved Words

The table below contains a list of all the reserved terms in JavaScript. They cannot be used as variables, functions, methods, loop labels, or object names in JavaScript.

abstractelseinstanceofswitch
booleanenumintsynchronized
breakexportinterfacethis
byteextendslongthrow
casefalsenativethrows
catchfinalnewtransient
charfinallynulltrue
classfloatpackagetry
constforprivatetypeof
continuefunctionprotectedvar
debuggergotopublicvoid
defaultifreturnvolatile
deleteimplementsshortwhile
doimportstaticwith
doubleinsuper

Multiple Variables Declaration

As seen in the examples above, the most typical approach to defining and initializing JavaScript variables is writing each variable on its line. Multiple variables, however, can be stated on a single line separated by a comma. In other words, you can only use one variable keyword (var, let, or const) and separate the variable names and values with commas.

Demo Example 1

let name, age, city;

You may also use comma-separated declarations to create a multi-line declaration, as demonstrated below:

Demo Example 2

let name = “eval”, 
age = 21, 
city = “New Delhi”;

Note: When declaring a variable in JavaScript, you can use several white spaces and line breaks.

Finally, the destructuring assignment may be used to define and initialize several variables in a single line, as seen below:

Demo Example 3

const [name, age, message] = ["eval", 21, "New Delhi"];
console.log(name); // "eval",
console.log(age); // 21
console.log(message); // "New Delhi"

Note: The destructuring assignment in the preceding code removes array items and assigns them to variables specified on the left side of the = assignment operator.

Initializing a Variable

After you’ve declared a variable, you may assign it a value. To initialize a variable, supply the variable name first, an equals sign (=), and then a value. You can assign a value to a variable either while it is being declared or after it has been declared.

Undefined variable 

occurs when a variable is declared but not assigned a value. The term “undefined” is not a keyword.

Demo Example: Undeclared and undefined in JavaScript

<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<h1>Undeclared Varialbe vs Undefined Variable</h1>
<div class="res"></div>
<div class="res"></div>
<button class="Btn">I'm a Button</button>
<h3>Click on button to access undeclared and undefined variable</h3>
<script>
   let click = document.querySelector(".Btn");
   let result = document.querySelectorAll(".res");
   let a;
   click.addEventListener("click", () => {
      result[0].innerHTML += "Accessing undefined variable = " + a;
      try {
         result[1].innerHTML = b;
      } catch (err) {
         result[1].innerHTML = "Accessing undeclared variable = " + err;
      }
   });
</script>
</html>

It should be noted that the term undeclared variable was previously used. Remember that this is not the same as an undefined variable.

Demo Example 1

var x = 10; 

Demo Example 2

var _x= x+5;

JavaScript Variable Scope

A variable’s scope is the area of your program where it is specified. Variables in JavaScript have just two scopes.

Global variables

They have global scope, which means they may be declared anywhere in your JavaScript code.

Local Variables

A local variable is only accessible within the function in which it is declared. The arguments of a function are always local to that function.

A local variable with the same name takes priority over a global variable with the same name within the body of a function. When you define a local variable or function parameter with the same name as a global variable, the global variable is essentially hidden.

Demo Example: Local and Global variable in JavaScript

<!DOCTYPE html>
<html>
<body>
	<h1>Demo: JavaScript Global and Local Variables </h1>
	<script>
		var gVar = "I'm global variable." // global variable
			function fx(){
			var lVar = "I'm local variable."; //local variable
			alert(gVar + " " + lVar); // access global and local variable
		}
      		fx();
		alert(gVar);//can access global variable
		alert(lVar); //error: can't access local variable
    </script>
</body>
</html>

Article Category: JavaScript Tutorials

More JavaScript Tutorials

Exit mobile version