Constants and Variables in JavaScript

Intro To This Week's Topic

We're talking about Constants and Variables in JavaScript (JS) and taking a look at the syntax and rules for declaring them.

The syntax for JavaScript is based off of Java, but is also influenced by Awk, Perl, and Python. JS is case-sensitive and uses the Unicode character set. Therefore, a variable named number is different from one named Number.

In JS, instructions are called statements and are separated by a semicolon (;) , like in Java. While a semicolon is not necessary if statements are written on separate lines, it is best practice to do so.

There are two types of declarations made in JS; Variables var, and Constants const. We will dive into each one below.

Variables (var)

Naming Variables

A JavaScript variable's name, or identifier, must adhere to certain rules:
  • It must start with a letter, underscore (_), or dollar sign ($).
  • Characters after the first can be digits (1-9).
  • Because JS is case-sensitive, A-Z are different characters from a-z.
  • ISO 8859-1 or Unicode letters such as å and ü can be used in identifiers.
  • Identifiers cannot be reserved words. See the list on Mozilla's MDN Web Docs.
Some examples of legal names are Number_hits, temp99, $credit, and _name.

Declaring & Assigning Variables

Declaring a variable in JavaScript is a bit different than in Java. The biggest difference is that you don't identify the variable type (int, String, char, Boolean, etc.) in the declaration.

For example, in Java we would use the following line of code to declare an int and assign a value of 10:
private int myVariable = 10;
In JavaScript, we simply write:
var myVariable = 10;
This syntax can be used for global and local variables. Also, you do not have to assign a value to the variable when you declare it. Unassigned variables are given the default value of undefined, which is interpreted as false in a boolean context and NaN in a numeric context.

For example, this code executes myFunction() because the array is undefined.
var myArray = [];
if (!myArray[0]) myFunction();
Attempting to access an undefined variable will result in a ReferenceError exception.

Since you can declare variables of different data types using var, they can be declared in one line of code.
var carOwner = "John Doe", carModel = "Honda", carPrice = 10000, newCar = false; 
Even though this is acceptable, it is considered best practices to list each variable declaration on its own line.

Finally, variables should be declared at the top of their scope (see below for "scope") and unassigned variables should be listed AFTER assigned variables.
var carOwner = "John Doe";
var carPrice;

Variable Scope

Variables declared outside of a function are considered global variables, while variables declared within a function are considered local variables.

However, when a block statement (identified by curly braces {}) like an if, while or for, contains a var declaration it can be used in a global context.
if (true) {
     var x = 5;
}
console.log(x); // x is 5
This behavior changes with the use of the let declaration introduced in ECMAScript 2015. To make a variable local to a block of code, like the above if statement, use the let declaration to prevent it from becoming a global variable.
if (true) {
     let y = 5;
}
console.log(y); // ReferenceError: y is not defined
Note: Global variables are properties of the global object, which in web pages is window, so you can set and access global variables using window.variable.

Variable Hoisting

A unique characteristic of JavaScript is the ability to refer to a variable declared later without throwing an exception. This is known as hoisting. Essentially, the variable declaration is lifted to the top of the function or statement, yet the assignment does not come with it. This will result in an undefined rather than an exception.
console.log(x === undefined); // true
var x = 3;

Constants (const)

Constants in JavaScript are the equivalent of a final variable Java. Once they are assigned, they become a read-only variable.

Declaring & Assigning Constants

Constants have similar naming conventions as Variables. They must start with a letter, underscore or dollar sign ($) and can contain alphabetic, numeric, or underscore characters.
const PI = 3.14;
A constant must be initialized to a value and cannot be re-assigned in the script.

You cannot declare a constant with the same name as a function or variable within the same scope.
// THIS WILL CAUSE AN ERROR
function f() {};
const f = 5;
Though properties of objects assigned to constants are not protected, which means this code runs without error.
const MY_OBJECT = {'key': 'value'};
MY_OBJECT.key = 'otherValue';

Comments

  1. Does JavaScript have the convention of using commas in large numbers? I wasn't sure when you wrote "carPrice = 10,000" whether JavaScript would complain or not. Most languages do not do this. Just wondering.

    ReplyDelete
    Replies
    1. Thank you for pointing that out. It was a typo on my part, that I now corrected.

      Delete

Post a Comment