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 arestring
,number
,boolean
,undefined
,null
, andSymbol
. 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, likestring
. This can be a little confusing, but hopefully this article will clear some of this confusion up for you.
string
Astring
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 anumber
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 ofstrings
!
constname="Preston Lamb";constjob="web developer";constcapital_A="A";constemptyString="";
All of the above are examples ofstrings
in JavaScript. As I previously mentioned, astring
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:
constfirstString="Here is a string";constsecondString="Here is the second string";constcombinedString=firstString+""+secondString;console.log(combinedString);// Here is a string Here is the second stringconsole.log(1+"."+firstString);// 1. Here is a stringconsole.log(firstString.charAt(0));// Hconsole.log(firstString.length);// 16console.log(firstString.substring(0,4));// Here
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);// falseconsole.log("a"==="a");// trueconsole.log("a"<"b");// true
number
In JavaScript, anumber
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, likeint
for a whole number, orfloat
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);// 4console.log(4-2);// 2console.log(2*2);// 4console.log(2/2);// 1console.log(2%2);// 0
You can also use math shorthand operations in JavaScript. The following are examples:
letval=0;val+=4;console.log(val);// 4val-=2;console.log(val);// 2val*=3;console.log(val);// 6val/=2;console.log(val);// 3val%=3;console.log(val);// 0
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.
constnumber=1;console.log(number+"1");// 11
boolean
A JavaScriptboolean
represents one of two values:true
orfalse
. They can be declared and initialized with a value oftrue
orfalse
, or by providing an expression will evaluate totrue
orfalse
. Here are some examples of defining and initializingboolean
variables.
letisGreaterThan100=50>100;// falseletisLessThan10=5<10;// trueletequals5=5===5;// true
booleans
are perfect for defining how a UI displays, or if a certain piece of code should be run (usingif
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 thannull
. Examples ofundefined
are as follows:
letmyVar;console.log(myVar);// undefinedfunctionsayHi(name){console.log(`Hi${name}!`);}sayHi();// Hi undefined!
Checking forundefined
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 passnull
overundefined
, 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 ofnull
:
functionconstructName(firstName,middleName,lastName){letname="";name=`${firstName}`;if(middleName){name=`${name}${middleName}`;}name=`${name}${lastName}`;returnname;}constfullName=constructName("Preston",null,"Lamb");console.log(fullName);// Preston Lamb
In the above example, I didn’t want to pass in a value formiddleName
, so I passed innull
. I could have passedundefined
, but in these situationsnull
is more frequently used.
Symbol
Symbol
values are new to JavaScript as of ES2015. They are created by using theSymbol
function, and are guaranteed to be unique. For example, twoSymbol
variables, even created in the exact same manner, won’t equal each other:
letsym1=Symbol("sym");letsym2=Symbol("sym");console.log(sym1===sym2);// false
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 astring
. Here’s an example of that:
letsym=Symbol("my symbol");alert(sym);// TypeError: Cannot convert a Symbol value to a `string`
If you’d like to do that and print out theSymbol
, you’ll have to do the following:
letsym=Symbol('my symbol')';alert(sym.toString()); // Symbol(my symbol)
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)
For further actions, you may consider blocking this person and/orreporting abuse