Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 3.2Variables in JavaScript

JavaScript supports the concept of variables.

What a variable is

A variable can be seen as a container that is used to store data. Most programming languages support variables as well as constants.

Variables are instantiated with an initial value or instantiated without a value. They can then be assigned a value at a later stage or the value stored can be retrieved.

Variables in JavaScript

A variable in JavaScript is signified by the var keyword. The following sample stores the value of 50 inside a variable called 'number' and then it places the value on the console:

JavaScript
var number = 50;
console.log(number);

Constants in JavaScript

Constants differ from variables because of the fact that once they have been set they cannot be changed. Constants that exist outwith computer science include Planck's constant (6.626×10-34 j/s) and the speed of light (2.98×108m/s).

Unlike most languages, JavaScript does not feature constants by default. One way of achieving constants in JavaScript is to define a function as follows that would essentially define a constant:

JavaScript
function define_constant(name, value) {
	Object.defineProperty(window, name.toUpperCase(), {"value" : value, "writable" : false});
}
define_constant("Test", 50);
console.log(TEST);
Feedback 👍
Comments are sent via email to me.