JAvascript

Variables in Javascript

Variables

A variable is a program container that holds a certain value to be used by the program.

In some programming languages, such as Java, a variable is declared to hold a specific value type, such as integer or string. This is called static typing and it can be beneficial for maintaining program integrity by preventing unintended value type conversions.

However JavaScript offers weak typing or dynamic typing. JavaScript is a loosely typed or a dynamic language, which means that variables in JavaScript are not directly tied to any particular value type, and that any variable can be assigned (and re-assigned) a value of any type. This can be beneficial for program flexibility by allowing a single variable to hold a value no matter what type it may take at any given moment in the program’s logic flow.

Declaring variables with var

The var keyword is used to declare variables, optionally initializing them to a value. When a script is run, variable declarations are processed prior to any code execution. A variable can be declared without being initialised and it assumes the value undefined.


// Declaring a variable called age
var age;
console.log(age); // undefined

// Initialising the variable with a value of 33
age = 33;
console.log(age); // 33

Optionally variable declaration and initialisation can take place in the same line.

var age = 33;

With var you can re-declare a variable without the variable losing its value unless if you re-assign it a new value.

var age = 32;
var age;
console.log(age); // 32
var age = 32;
var age = 33;
console.log(age); // 33

Declaring and assigning multiple variables:

var cdTemp, cpuTemp = 32, ramTemp = 42;
console.log(cdTemp); //prints undefined
console.log(cpuTemp); //prints 32
console.log(ramTemp); //prints 42

Declaring variables with let

The let statement declares a block scopeed local variable and optionally initialises it to a value. The let keyword was introduced in ES6. Before that, there was only the var keyword for creating variables.

Unlike var, the let keyword declares variables that are limited in scope to the block, statement, or expression on which it is used.

{
	var student1 = "Isaac";
}

// variable student1 accessible outside the block
console.log(student1); // Isaac

{
	let student1 = "Isaac";
}

// variable student1 not accessible outside the block
console.log(student1); // ReferenceError: student1 is not defined

Another difference between var and let is that let doesn’t allow you to re-declare a variable. It leads a "syntax error":

let age = 32; 
let age; 
console.log(age);

//Output:

/* let age; 
       ^^^

SyntaxError: Identifier 'age' has already been declared*/

Declaring and assigning multiple variables:

lets cdTemp, cpuTemp = 32, ramTemp = 42;
console.log(cdTemp); //prints undefined
console.log(cpuTemp); //prints 32
console.log(ramTemp); //prints 42

Undeclared variables

JavaScript allows us to assign values to undeclared variables, unless it is in strict mode. An undeclared variable implicitly becomes a global variable when it is assigned a value. For example, lets just assign a value of 34 to a variable age without first declaring it.

// assign a value to an undeclared variable
age = 34;
console.log(age); // 34

However, in strict mode, you get a reference error.

"use strict"
// assign a value to an undeclared variable
age = 34;
console.log(age); // ReferenceError: age is not defined

Variable hoisting

In JavaScript, variable declarations are processed before the execution of any code. This means if you declare a variable at any point in the code, it is the same as if you declared it at the top. This is known as "hoisting".

Let us look at some interesting examples here. An undeclared variable doesn’t exist until it is assigned a value. Which means trying to log it in console will only give us an error.

console.log(name); // ReferenceError: name is not defined

However if you declare the variable below that code, the error ceases to exist. Lets see:

console.log(name); // undefined
var name;

Now the variable exists (with an undefined value) when we try to log it even though it was declared after logging it. That is because the variable declaration was "hoisted" to the top of the code. The code was executed as if it was written like:

var name;
console.log(name); // undefined

However variable declarations using let do not support variable hoisting:

console.log(name); // ReferenceError: name is not defined
let name;

Variable types

JavaScript offers dynamic typing which means that a variable can be re-assigned any data type without producing an error.

//create variable age and assign it an integer
let age = 32;
console.log(age); //prints 32

//reassign it a string
age = "thirty two";
console.log(age); //prints thirty two

//reassign it a boolean
age = false;
console.log(age); //prints false

Declaring constants with const

A constant also holds a value like a variable does, but unlike a variable, the value can’t be changed after initialization. By convention, constants are usually given uppercase names.

If you try to change the value of a constant,

//declare a constant with value 25
const AVRG_TEMP = 25;

//re-assign the constant
AVRG_TEMP = 24;

you will get the following error:

AVRG_TEMP = 24;
          ^
TypeError: Assignment to constant variable.

What is shown by the code above, is actually the biggest advantage of using constants; it makes it harder to accidentally change the value of something that shouldn’t change. Therefore if there is a value you wish to remain unchanged (such as a value to be used as a reference value) its better to declare it as a constant.

Identifiers

Variable names, constant names and function names, are called identifiers.

Identiers have the following naming rules:

  1. Identifiers should start with either a letter (uppercase or lowercase), a dollar sign ($), or an underscore (_).
  2. Identifiers can consist of letters, numbers, the dollar sign ($), and underscore (_).
  3. Unicode characters are also allowed in identifiers (for example, π or ö).
  4. An identifier cannot be a reserved word.

Examples of allowed identifiers:

let sydney;
let $cash;
let _under;

Examples of unallowed identifier:

let @error;
let for;

Literals

A literal is a value directly provided to a either a variable or constant.

Examples of literals:

const CPU_CORES = 8; //8 is a numerical literal
let curUsers = 10; //10 is a numerical literal
let userName = "Sydney"; //Sydney is a string literal

String literals require quotes around them.