Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Preston Lamb
Preston Lamb

Posted on • Originally published atprestonlamb.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 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, likeString, 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="";
Enter fullscreen modeExit fullscreen mode

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
Enter fullscreen modeExit 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);// falseconsole.log("a"==="a");// trueconsole.log("a"<"b");// true
Enter fullscreen modeExit fullscreen mode

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
Enter fullscreen modeExit fullscreen mode

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
Enter fullscreen modeExit 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.

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

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
Enter fullscreen modeExit fullscreen mode

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!
Enter fullscreen modeExit fullscreen mode

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
Enter fullscreen modeExit fullscreen mode

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
Enter fullscreen modeExit 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 astring. Here’s an example of that:

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

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)
Enter fullscreen modeExit 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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Preston Lamb is a full stack JavaScript developer, Angular GDE, ngChampion writer for the ng-conf blog, & co-organizer of the Angular Community Meetup.
  • Location
    Roy, UT
  • Education
    BS in Computer Science from Utah State University
  • Work
    Software Developer at MotivHealth
  • Joined

More fromPreston Lamb

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp