Apps/Gaming

JavaScript variables

You have probably heard it said that JavaScript is a loosely typed language. That is because developers do not have to specify the data type of a variable in JavaScript. But that does not mean that JavaScript does not have variables (or data types for that matter); it is just that the JavaScript interpreter chooses the data type of the variable based on its value and generates the executable code accordingly. In this web development tutorial, we will look at how to declare and set variables in JavaScript, some scoping basics, hoisting, as well as what types of names are best.

Want to learn JavaScript web development in an online course? We have a list of the Best Online Courses to Learn JavaScript to help you get started.

How to Declare and Set a JavaScript Variable

Before we get into the business of declaring and setting a variable in JavaScript, we should establish that there are two variable scopes in JavaScript: local and global.

Local variables are declared inside a function or block using the const, letor var keywords and are accessible only within that function or block:

function aFunction() { var myLocalVar = 99; //local variable console.log(myLocalVar); //99 } //ReferenceError: myLocalVar is not defined console.log(myLocalVar);

Meanwhile, global variables are those that are declared without the const, letor var keywords or explicitly added to the global window object. As you would expect, once declared, global variables are accessible from anywhere in the script. They can be declared outside the function or explicitly added to the window object:

globalVar=”I am global!”; function aFunction() { var myLocalVar = 99; //local variable console.log(myLocalVar); //99 //Inside aFunction: I am global! console.log(‘Inside aFunction: ‘ + globalVar); window.anotherGlobalVar = 4.5; } aFunction(); //Outside a function: I am global! console.log(‘Outside a function: ‘ + globalVar); //anotherGlobalVar = 4.5 console.log(‘anotherGlobalVar=” + anotherGlobalVar);

JavaScript const, let, and var Keywords

From JavaScript’s inception in 1995 to 2015, the var keyword was the only way to declare a local variable. Then the const other let keywords were added to JavaScript as part of the ECMAScript 2015 specification. Web developers should always use it const other let, unless you need your code to run in really old browsers. In fact, you should always declare variables with const, if possible. This declares it as a constant, meaning that its value cannot be changed. Otherwise, if you expect to be modifying the variable’s value, then go ahead and use let.

Reading: Working with Output in JavaScript

Declaring Multiple Variables in JavaScript

In JavaScript, we can declare multiple variables in one line:

let bandMember1 = “John’, age = 29, job = ‘vocalist’;

Depending on how many variables you are declaring, you can wind up with a very long line of code. For increased readability, it is recommended that programmers use a single line per variable:

let bandMember1 = ‘John’, age = 29, job = ‘vocalist’;

Some developers prefer to use the “comma-first” style:

let bandMember1 = ‘John’ , age = 29 , job = ‘vocalist’;

Either works!

Hoisting and its Effect on Variables in JavaScript

JavaScript Hoisting is a bit of a complex subject, but it does relate to variable declaration, in particular using the var keywords. Hoisting refers to a process performed by the JavaScript interpreter, prior to execution of the code, whereby it moves the declaration of functions, variables, and classes to the top of their scope, so that you can refer to them before they are declared. Without it, the following code would not work because the getName() function is called before it is declared:

getName(bandMember1); function getName(name) { console.log(`My name is ${name}`); }

The same holds true for variables. Programmers can refer to a variable even before it is declared, and they will contain a value of undefined, just as it would after declaration, but before initialization:

console.log(num); // Returns ‘undefined’ from hoisted var declaration (not 6) var num = 6; // Initialization and declaration. console.log(num); // Returns 6 after the initialization line.

With respect to the var keyword, it is the only one that lets you redeclare the same variable. In fact, you can declare the same variable as many times as you like!

function aFunction() { var myLocalVar = 99; //local variable console.log(myLocalVar); //99 var myLocalVar = 100; console.log(‘The new myLocalVar=” + myLocalVar); //100 }

You can read more about hoisting here.

Naming Rules and Conventions for JavaScript Variables

Variable names in JavaScript are called identifiers. These can be short names like x other y or more descriptive names like age, sumor total volume. The general rules for constructing names for variables (unique identifiers) are:

  • can contain letters, digits, underscores, and dollar signs, but must begin with a letter
  • can also begin with $ or _
  • names are case sensitive
  • reserved words (like class, throw, if) cannot be used as names

Although following the above rules will keep the compiler errors away, web developers should not just be choosing names willy-nilly. Here are a few best practices to follow when naming your JavaScript variables:

Reading: Top Collaboration Tools for Web Developers

Final Thoughts on JavaScript Variables

In this web development tutorial, we learned how to declare and set variables, some scoping basics, hoisting, as well as what types of names are best in JavaScript. If you would like to see the topics presented in action, there is a codepen demo for you to explore.

read more JavaScript tutorials and web development tips.

Related posts

Hyper-casual bible: top resources for making a hit game

TechLifely

Java Tools to Increase Productivity

TechLifely

LiquidPlanner Project Management Review

TechLifely

Leave a Comment