DEV Community

Preston Lamb
Preston Lamb

Posted on • Originally published at prestonlamb.com on

JavaScript Primitive Types

tldr;

JavaScript has built-in, primitive types. The variables that you create have types, whether you know it or not. Understanding these primitive types and what’s going on behind the scenes will help you understand how to better write your applications. The primitive types that we’ll talk about in this article are string, number, boolean, undefined, null, and Symbol. We’ll go over each of these and give some examples of each below.

A primitive type in JavaScript is data that is not an object and has no methods. JavaScript also has global objects, like String, that are different than related primitive types, like string. This can be a little confusing, but hopefully this article will clear some of this confusion up for you.

string

A string in JavaScript is a collection of characters. That collection of characters can have a length of 0, or it can be much longer. As far as I can tell, there is no upper limit on string length. There were some references to making sure that the length of the string does not exceed the biggest number that can be stored in a number variable. We’ll talk more about that later, but the maximum value for a number in JavaScript is (2^53)-1.

Let’s look at some examples of strings!

const name = "Preston Lamb";
const job = "web developer";
const capital_A = "A";
const emptyString = "";
Enter fullscreen mode Exit fullscreen mode

All of the above are examples of strings in JavaScript. As I previously mentioned, a string can have 0 characters in it, as long as it’s declared with quotation marks.

There is also built in functionality for strings, such as concatenation, getting substrings, getting the length, or getting a character at a specific location in the string. Here are some examples of that:

const firstString = "Here is a string";
const secondString = "Here is the second string";
const combinedString = firstString + " " + secondString;

console.log(combinedString); // Here is a string Here is the second string
console.log(1 + ". " + firstString); // 1. Here is a string
console.log(firstString.charAt(0)); // H
console.log(firstString.length); // 16
console.log(firstString.substring(0, 4)); // Here
Enter fullscreen mode Exit fullscreen mode

Something interesting to note in the above examples is that you can add numbers and strings together. If you do this, the number will be concatenated with the string, as if it was a string itself. This can be tricky and can mess you up if you’re not prepared for it.

Comparison operators can also be used with strings:

console.log(firstString === seconString); // false
console.log("a" === "a"); // true
console.log("a" < "b"); // true
Enter fullscreen mode Exit fullscreen mode

number

In JavaScript, a number is a numeric type “in the double-precision 64-bit floating point format (IEEE 754)”. Basically, this means that a JavaScript number value can be between -(2^53 -1) and (2^53)-1. Other programming languages may have different types depending on the numerical value, like int for a whole number, or float for a floating point number. But in JavaScript this is all grouped together.

All the normal mathematical operations can be used on two numbers, like +, -, x, ÷, and %. Here are some examples:

console.log(2 + 2); // 4
console.log(4 - 2); // 2
console.log(2 * 2); // 4
console.log(2 / 2); // 1
console.log(2 % 2); // 0
Enter fullscreen mode Exit fullscreen mode

You can also use math shorthand operations in JavaScript. The following are examples:

let val = 0;
val += 4;
console.log(val); // 4
val -= 2;
console.log(val); // 2
val *= 3;
console.log(val); // 6
val /= 2;
console.log(val); // 3
val %= 3;
console.log(val); // 0
Enter fullscreen mode Exit fullscreen mode

Remember that if you try to add a number with a string, the number will be treated as a string and concatenated with the other string. This is true even if the only content of the string is a number. Look at the below example.

const number = 1;
console.log(number + "1"); // 11
Enter fullscreen mode Exit fullscreen mode

boolean

A JavaScript boolean represents one of two values: true or false. They can be declared and initialized with a value of true or false, or by providing an expression will evaluate to true or false. Here are some examples of defining and initializing boolean variables.

let isGreaterThan100 = 50 > 100; // false
let isLessThan10 = 5 < 10; // true
let equals5 = 5 === 5; // true
Enter fullscreen mode Exit fullscreen mode

booleans are perfect for defining how a UI displays, or if a certain piece of code should be run (using if statements, for example).

undefined

undefined is the value assigned to variables when they are declared but not initialized, or to arguments for functions that aren’t present. undefined is different than null. Examples of undefined are as follows:

let myVar;
console.log(myVar); // undefined

function sayHi(name) {
  console.log(`Hi ${name}!`);
}

sayHi(); // Hi undefined!
Enter fullscreen mode Exit fullscreen mode

Checking for undefined is a good idea inside functions that are expecting certain values so that you don’t try and do some piece of logic if the argument wasn’t passed in.

null

In JavaScript, null refers to the absence of a value. Usually this is done intentionally. Some functions may have optional arguments, and in those situations it is a good idea to pass null over undefined, at least if the argument you don’t want to pass is in the middle of a list of arguments. Here are some examples of the use of null:

function constructName(firstName, middleName, lastName) {
  let name = "";
  name = `${firstName}`;

  if (middleName) {
    name = `${name} ${middleName}`;
  }

  name = `${name} ${lastName}`;

  return name;
}

const fullName = constructName("Preston", null, "Lamb");
console.log(fullName); // Preston Lamb
Enter fullscreen mode Exit fullscreen mode

In the above example, I didn’t want to pass in a value for middleName, so I passed in null. I could have passed undefined, but in these situations null is more frequently used.

Symbol

Symbol values are new to JavaScript as of ES2015. They are created by using the Symbol function, and are guaranteed to be unique. For example, two Symbol variables, even created in the exact same manner, won’t equal each other:

let sym1 = Symbol("sym");
let sym2 = Symbol("sym");

console.log(sym1 === sym2); // false
Enter fullscreen mode Exit fullscreen mode

Symbols are always guaranteed to be unique. If you need a guaranteed unique value, Symbol is the perfect option.

Lastly, Symbols do not have an automatic conversion to a string. Here’s an example of that:

let sym = Symbol("my symbol");
alert(sym); // TypeError: Cannot convert a Symbol value to a `string`
Enter fullscreen mode Exit fullscreen mode

If you’d like to do that and print out the Symbol, you’ll have to do the following:

let sym = Symbol('my symbol')';
alert(sym.toString()); // Symbol(my symbol)
Enter fullscreen mode Exit fullscreen mode

Conclusion

It’s important to have an understanding of these primitive types in JavaScript. Selecting and using the proper types for variables and arguments of functions will help to limit the number of mistakes made. It will help your applications run how you’re expecting them too with as few negative side effects as possible.

Top comments (0)