JavaScript Tutorial Series – Variables

In JavaScript, variable names must start with a letter or underscore, are case sensitive and multiple words should be camel cased, example: aVariableName. Variable names may only contain letters, numbers and underscores.

JavaScript determines what type a variable is. There are primitive and complex types. Valid primitive types include string, number, boolean, null, symbol and undefined. Variables are defined as either var, let or const. Variables defined as var are hoisted to the top of the defining function. Variables defined using let have block scope, so they are only visible within the enclosing scope, such as within a for loop or if statement. Variables defined using const also have block scope and can not be reassigned a new value. They are constant. Since let was introduced, using var isn’t really necessary. Using let also protects from unintentionally re-declaring a variable with the same name. For example, the code below using var will not throw an error:

 var diameter = 11; diameter += 5; console.log(diameter); var diameter = 12; console.log(diameter);

However using let will throw an error when declaring a variable with the same name as an already declared variable with that name.

 let diameter = 11; diameter += 5; console.log(diameter); let diameter = 12; console.log(diameter);

 let diameter = 13;  // A number let radius = 6.5;   // A number let shape = "Circle"; // A string let large = false; // A boolean let small = x; // Undefined

Semi-colons at the end of the declaration are optional. I prefer to use them as they give a clear indication of the end of a statement.

Assigning a variable a different value with a different type than it’s previous definition, changes the variable’s type.

 radius = '6';  // Radius is now a string

The type of a variable can be found by:

 typeof radius;

A variable may be displayed on the screen by using the built in console function:

 console.log(typeof radius);

To convert a variable of one type to another type, cast the variable. Examples:

 let str_cast = diameter.toString(); let int_cast = parseInt(shape); let float_cast = parseFloat(diameter);

Number will also cast a string to a number, example;

 let num_cast = Number(diameter);

Complex variable types are function and object. Object is returned for null, arrays and objects, but not functions. Functions and objects will be discussed in later lessons.

Implementation:

Inside the javascript_tutorial.js file created in the JavaScript set up tutorial, add the following lines that are in bold:

// JavaScript Tutorial /* * This file will add JavaScript * to a website. */ (function() {   let doc = document; })();

The JavaScript tutorial series starts with this post.

(paid links)
More JavaScript