Using JavaScript Variables and Types

You are currently viewing Using JavaScript Variables and Types

The let keyword is used to declare variables and, optionally, assign a value to the variable in a single statement. Variables declared with let are scoped to the region of code in which they are defined, as shown in the example.

let messageFunction = function (name, weather) {
 let message = "Hello, Adam";
 if (weather == "sunny") {
 let message = "It is a nice day";
 console.log(message);
 } else {
 let message = "It is " + weather + " today";
 console.log(message);
 }
 console.log(message);
}
messageFunction("Adam", "raining");

In this example, there are three statements that use the let keyword to define a variable called message. The scope of each variable is limited to the region of code that it is defined in, producing the following results:

It is raining today

Hello, Adam

This may seem like an odd example, but there is another keyword that can be used to declare variables: var. The let keyword is a relatively new addition to the JavaScript specification that is intended to address some oddities in the way var behaves.

let messageFunction = function (name, weather) {
 var message = "Hello, Adam";
 if (weather == "sunny") {
 var message = "It is a nice day";
 console.log(message);
 } else {
 var message = "It is " + weather + " today";
 console.log(message);
 }
 console.log(message);
}
messageFunction("Adam", "raining");

When you save changes in the example, you will see the following results:

It is raining today

It is raining today

The problem is that the var keyword creates variables whose scope is the containing function, which means that all the references to the message are referring to the same variable. This can cause unexpected results for even experienced JavaScript developers and is the reason that the more conventional let keyword was introduced.

Using Variable Closure

If you define a function inside another function—creating inner and outer functions—then the inner function is able to access the variables of the outer function, using a feature called closure, as demonstrated in the following example.

let myFunc = function(name) {
 let myLocalVar = "sunny";
 let innerFunction = function () {
 return ("Hello " + name + ". Today is " + myLocalVar + ".");
 }
 return innerFunction();
};
console.log(myFunc("Adam"));

The inner function in this example is able to access the local variables of the outer function, including its name parameter. This is a powerful feature that means you don’t have to define parameters on inner functions to pass around data values, but caution is required because it is easy to get unexpected results when using common variable names like counter or index, where you may not realize that you are reusing a variable name from the outer function. This example produces the following results:

Hello Adam. Today is sunny.

Using the Primitive Types

JavaScript defines a basic set of primitive types: string, number, and boolean. This may seem like a shortlist, but JavaScript manages to fit a lot of flexibility into these three types.

Working with Booleans

The boolean type has two values: true and false. The following example shows both values being used, but this type is most useful when used in conditional statements, such as an if statement. There is no console output from this listing.

let firstBool = true;
let secondBool = false;



Working with Strings

You define string values using either the double-quote or single quote characters, as shown in the following example.

let firstString = "This is a string";
let secondString = 'And so is this';

The quote characters you use must match. You can’t start a string with a single quote and finish with a double quote, for example. There is no output from this listing. JavaScript provides string objects with a basic set of properties and methods, the most useful of which are described in the following Table.

NameDescription
length This property returns the number of characters in the string.
charAt(index) This method returns a string containing the character at the specified index
concat(string) This method returns a new string that concatenates the string on which the method is called and the string provided as an argument.
indexOf(term, start) This method returns the first index at which term appears in the string or -1 if there is no match. The optional start argument specifies the start index for the search.
replace(term, newTerm) This method returns a new string in which all instances of term are replaced with newTerm.
slice(start, end) This method returns a substring containing the characters between the start and end indices.
split(term) This method splits up a string into an array of values that were separated by term.
toUpperCase()
toLowerCase()
These methods return new strings in which all the characters are uppercase or lowercase.
trim() This method returns a new string from which all the leading and trailing whitespace characters have been removed.

Using Template Strings

A common programming task is to combine static content with data values to produce a string that can be presented to the user. The traditional way to do this is through string concatenation, which is the approach I have been using in the examples so far in this post, as follows:

...
let message = "It is " + weather + " today";
...

JavaScript also supports template strings, which allow data values to be specified inline, which can help reduce errors and result in more natural development experience. In the following shows the use of a template string

let messageFunction = function (weather) {
 let message = `It is ${weather} today`;
 console.log(message);
}
messageFunction("raining");

Template strings begin and end with backticks (the ` character), and data values are denoted by curly braces preceded by a dollar sign. This string, for example, incorporates the value of the weather variable into the template string:

...
let message = `It is ${weather} today`;
...

This example produces the following output:

It is raining today

Working with Numbers

The number type is used to represent both integer and floating-point numbers (also known as real numbers). The following example provides a demonstration.

let daysInWeek = 7;
let pi = 3.14;
let hexValue = 0xFFFF;

You don’t have to specify which kind of number you are using. You just express the value you require, and JavaScript will act accordingly. In the listing, I have defined an integer value, defined a floating-point value, and prefixed a value with 0x to denote a hexadecimal value.



Leave a Reply