Computer Science

Javascript Primitive Data Types

JavaScript primitive data types are the basic building blocks of the language and include numbers, strings, booleans, null, undefined, and symbols. These data types are immutable and directly hold a value. They are not objects and do not have methods. Primitive data types are stored by value, meaning that when they are assigned to a variable, the actual value is copied.

Written by Perlego with AI-assistance

11 Key excerpts on "Javascript Primitive Data Types"

  • LPI Web Development Essentials Study Guide
    • Audrey O'Shea(Author)
    • 2023(Publication Date)
    • Sybex
      (Publisher)
    A value's data type determines what can and cannot be done with that data. In JavaScript, there's no need to declare the type of data when it is entered, because JavaScript is a dynamically typed language that automatically determines the variable's data type for you. Although this makes writing code much easier, it can occasionally lead to bugs related to data type when the code is run.

    Primitive Types

    Primitive data types are built into most programming languages. They are basic in nature and may be used to build more sophisticated data types, as you'll see in the next section. JavaScript has eight primitive data types, shown in Table 14.2 .
    TABLE 14.2
    Primitive data types
    Type Description
    Boolean Logical, true or false, 1 or 0.
    BigInt Big integer, a number beyond what's considered “safe.” Cannot be fractional numbers.
    Null Empty, but defined.
    Number Positive floating point (decimal anywhere) numbers between 2–1074 and 21024 .
    String Alphanumeric characters not treated as numbers.
    Symbol Creates a unique symbol for a value within a program.
    Undefined The absence of a value—for example, a variable defined without its value (let x; ) creates the variable but with no value assigned.
    A variable's value type within a JavaScript program can change as its value changes. For example, let a = "apple"; assigns the string type to variable a. Later in the program, let a = 10; will change a 's type to number. Changing it again with a statement like let a = true returns the variable type of Boolean. If however, you write the statement let a = "true"; or let a = "10"; , then a will return the variable type of string. The difference between a = true and a = "true" is the quotes. The quotes turn the Boolean value of logical true to a text string.
    At any time you can tell what type a variable is using the typeof command. For example, let a = "apple"; console.log(typeof a); outputs string on the console log because the quotes tell the program that what's inside is a string.
    Data types null and undefined are special. They might look the same at first glance, but they are not. Neither null nor undefined is equal to zero. undefined means that the variable has been declared, but no value has been assigned. For example, let b; console.log b;
  • Clean Code in JavaScript
    eBook - ePub

    Clean Code in JavaScript

    Develop reliable, maintainable, and robust JavaScript

    Primitive and Built-In Types

    So far, we have explored the meaning of clean code from several different perspectives. We've explored how the code we write allows our users to wield remarkable complexity by leveraging abstractions. We've gone on to discuss the tenets of clean code, such as reliability and usability, and the various traps and challenges to watch out for when pursuing these goals.
    In this chapter, we'll be exploring the JavaScript language itself, in great detail, including both the more common language constructs and the more obscure and confusing aspects. We'll be applying our accrued wealth of knowledge about clean code to all these parts of the language and will build an understanding of JavaScript that's tailored purely to the creation of clean code.
    We'll begin by looking at the most atomic part of JavaScript: the primitive values that serve as the building blocks for any program. Then, we'll move on to non-primitive values, known as objects . In our exploration of these types, we will, through examples, be exposing the semantics that make each type unique and the pitfalls to avoid in their usage. The crucial knowledge that we'll gain in this chapter will be applied in later chapters as we build up a truly complete knowledge of what it means to write clean code in JavaScript.
    By the end of this chapter, you should feel comfortable in the following topic areas:
    • Primitive types
    • Objects
    • Functions
    • Arrays and iterables
    • Regular expressions
    Passage contains an image

    Primitive types

    A primitive type in JavaScript is any value that is not an object and thus does not have any methods or properties. There are seven primitive types in JavaScript:
    • Number
    • String
    • Boolean
    • Undefined
    • Null
    • BigInt
    • Symbol
    In this section, we'll explore the common characteristics among these primitives and delve into each individual type to explore how it works and what potential hazards exist in its usage. We'll gain an appreciation for how the JavaScript language itself is just a set of distinct abstractions that, when wielded masterfully, can make easy work of any problem domain.
  • JavaScript from Beginner to Professional
    • Laurence Lars Svekis, Maaike van Putten, Codestars By Rob Percival(Authors)
    • 2021(Publication Date)
    • Packt Publishing
      (Publisher)
  • Variables cannot contain spaces, but they can use underscores. If you use a space, JavaScript doesn't recognize it as a single variable.
  • We will be using camel case here. This means that when we want to use multiple words to describe a variable, we will start with a lowercase word, then use a capital for every new word after the first word—for example: ageOfBuyer .
    Whatever the convention is in the place you are working, the key is consistency. If all naming is done in a similar format, the code will look cleaner and more readable, which makes it a lot easier to make a small change later.
    The value of your variable can be anything. Let's start with the easiest thing variables can be: primitives.

    Primitive data types

    Now you know what variables are and why we need them in our code, it is time to look at the different types of values we can store in variables. Variables get a value assigned. And these values can be of different types. JavaScript is a loosely typed language. This means that JavaScript determines the type based on the value. The type does not need to be named explicitly. For example, if you declared a value of 5, JavaScript will automatically define it as a number type.
    A distinction exists between primitive data types and other, more complex data types. In this chapter, we will cover the primitive type, which is a relatively simple data structure. Let's say for now that they just contain a value and have a type. JavaScript has seven primitives: String, Number, BigInt, Boolean, Symbol, undefined, and null. We'll discuss each of them in more detail below.

    String

    A string is used to store a text value. It is a sequence of characters. There are different ways to declare a string:
  • The JavaScript Workshop
    eBook - ePub

    The JavaScript Workshop

    A New, Interactive Approach to Learning JavaScript

    • Joseph Labrecque, Jahred Love, Daniel Rosenbaum, Nick Turner, Gaurav Mehla, Alonzo L. Hosford, Florian Sloot, Philip Kirkbride(Authors)
    • 2019(Publication Date)
    • Packt Publishing
      (Publisher)

    5. Beyond the Fundamentals

    Overview
    By the end of this chapter, you will be able to identify the difference between JavaScript's mutable and immutable types; manipulate each of the built-in data types confidently; convert data from one type to another; format data types for presentation; and differentiate between an expression and a statement.

    Introduction

    In the previous chapter, you were given a tour of JavaScript, its runtimes, and its history. Using a high-level topography, that chapter will have given you an idea as to what JavaScript is, what it can do, and its ubiquity within the internet software development industry.
    Understanding code can be difficult for beginners. JavaScript is no exception. Its flexibility, extensive language syntax, and varying coding patterns can prove daunting to the uninitiated.
    This chapter will take you a step closer to writing your own software applications in JavaScript. By explaining the fundamentals, you will be empowered to not only understand what scripts do, but how to reason about problems using JavaScript syntax.
    In this chapter, you will take a close look at JavaScript's type system. All programming languages have a type system. Types literally dictate the type of data stored in a variable or function parameter. Types are typically separated into two categories: primitive and complex types.
    In JavaScript, all primitive data types are immutable. This means that the value cannot be changed in memory. New values can be assigned to a variable, but the underlying data stored in memory cannot be modified directly. This differs from the case in languages such as C++, where values can be directly altered in memory using pointers and helper functions. In JavaScript, when passing a primitive value from one variable to another, the data is copied in memory to the new variable. Therefore, updating one variable does not affect the other.
    Complex data types work differently. They are also known as reference types. Reference types include the Object type and all of its derivatives, such as Array , Date , and Function
  • Quick JavaScript
    eBook - ePub
    Chapter 2 JavaScript The Bare Minimum
    DOI: 10.1201/9781003359609-2
    This chapter and Chapter 3 describe JavaScript simply as a language, without reference to Web programming. It is in two major parts:
    The Bare Minimum—This section is intended to get you started programming in JavaScript as quickly as possible. The best way to do that is to try things out as you go.
    In More Detail—This goes over the same material again, filling in a lot of the gaps. To some extent, it can also be used as a reference.

    2.1 Comments

    // introduces a comment that extends to the end of the line.
    Multi-line comments start with /* and end with */ .
    Inside a comment, // and /* have no special meaning (so you cannot “nest” comments). Inside a quoted string or regular expression, // and /* do not start a comment.

    2.2 Data Types

    2.2.1 Primitives

    There are eight data types:
    • A number may be written with or without a decimal point, but all numbers are stored as double precision floating point.
    • A bigint is an integer with an arbitrarily large number of digits.
    • The two boolean values are written as true and false .
    • A string may be enclosed in either single quotes, double quotes, or backticks (`). There is no “character” type.
    • A symbol is a value that is guaranteed to be unique; no other value is equal to it. A symbol is created by calling Symbol() or Symbol( name) , where name is a (not necessarily unique) value that may be helpful in debugging.
    • The undefined type has a single value, undefined . It is the value of a variable that has been declared but not yet given a value.
    • The null type has a single value, null , meaning that the value does not exist.
    • An object is any more complicated data type. Functions, arrays, sets, maps, regular expressions, errors, and dates are all special types of object, as are user-defined objects.
    The type of a value can be determined by typeof , which can be used as either an operator, typeof x, or as a function, typeof( x) . It will return, as a string, one of the type names given above (for example, "number"
  • HTML and CSS
    eBook - ePub

    HTML and CSS

    The Comprehensive Guide

    • Jürgen Wolf(Author)
    • 2023(Publication Date)
    • SAP PRESS
      (Publisher)
    window object in the web browser. Such global variables could override properties of the global object.
    The strict mode makes sure that the use of error-prone features of JavaScript is simply not allowed. This leads to a script abort for previously ignored errors (without "use strict" ).
    Passage contains an image

    17.5    Overview of JavaScript Data Types

    As you already know, unlike other languages such as C++ or Java, you don’t have to specify a data type when declaring variables because this is determined at runtime in JavaScript based on the value that has been passed.
    JavaScript defines multiple data types. The primitive types are string , number , boolean , and symbol , and the special types include undefined and null . In addition to the primitive data types, JavaScript also has the composite data type object for objects.
    You can determine the type of a variable using the typeof operator. Possible return values are string , number , boolean , object , function , symbol , and undefined .

    17.5.1    Number Data Type (Numbers)

    In JavaScript, there’s no difference between integers and floating-point numbers. According to the ECMAScript standard, there’s no specific data type for integers, and all data types for numbers are represented internally by JavaScript as 64-bit floating-point values. For example:
    let integerValue = 12345; console .log( typeof integerValue ); // Output: number let floatingPointValue = 123.123; console .log( typeof floatingPointValue ); // Output: number
    If a value doesn’t correspond to a correct numerical value, NaN (NaN = not a number ) will be used as the value. If the value range has been exceeded or fallen below, Infinity or ‐Infinity will be used as the value. For this reason, there are two constants: Number.POSITIVE_INFINITY and Number.NEGATIVE_INFINITY . If you want to determine the smallest or largest possible number you can use, the Number.MIN_VALUE and Number.MAX_VALUE
  • Decoding JavaScript
    eBook - ePub

    Decoding JavaScript

    A Simple Guide for the Not-so-Simple JavaScript Concepts, Libraries, Tools, and Frameworks (English Edition)

    You can also update the value of a variable, which already has a value by typing the variable name followed by an equals sign, and the new value. For instance:
    1. name = 'Cristiano Ronaldo';
      Code 1.9: Changing the value of a variable
    If you try to print the value of the name variable now, it will no longer be John Doe. The value of the name variable now will be Cristiano Ronaldo.

    Data types in JavaScript

    The data or the value that you store inside a variable can be of different types. For instance, in the preceding examples, we have seen numbers and text types. Unlike other programming languages, you don't require different keywords for different types of data in JavaScript. The different types of data in JavaScript are as follows:
    • Numbers : It comprises of whole numbers; for example, 30, or decimal numbers like 245.67. You don't need to put these values in quotes.
      1. var num1 = 45;
        Code 1.10: Number datatype
    • Strings : Strings are nothing but text. When you assign a string value to a variable, you need to wrap it with single-quotes or double-quotes.
      1. var name = 'John Doe';
        Code 1.11: String datatype
    • Booleans : Booleans have two values - true or false. You don't need to wrap the value in quotes. Booleans are mostly used for testing conditions. For instance, if the value of the boolean variable is true, then you can execute certain code, or else you can set some other code for execution. It can also contain an expression like 10>5 as the value. In this case, as numeric10 is greater than numeric 5, the value of the variable containing this expression will be true.
      1. var isNumber = true;
        Code 1.12: Boolean datatype
    • Arrays : Arrays are a complex data type that can store multiple values. Multiple values are stored inside square brackets and separated by commas. We will study arrays in more detail in Chapter 4: Arrays .
      1. var cars = ['BMW', 'Audi', 'Rolls Royce'];
        Code 1.13: Array datatype
    • Objects : Objects are also a complex data type which can store multiple values. However, unlike arrays, in objects, you can name the data that you are storing. Objects are used for modelling a real-life object. The multiple values are named and stored inside curly brackets.
      1. var employee = {name: 'John Doe', age: 24, city: 'London'} Code 1.14:
  • Beginning JavaScript
    • Jeremy McPeak(Author)
    • 2015(Publication Date)
    • Wrox
      (Publisher)
    2 Data Types and Variables
    WHAT YOU WILL LEARN IN THIS CHAPTER:                
    • Representing data in code
    • Storing data in memory
    • Making calculations
    • Converting data
    WROX.COM CODE DOWNLOADS FOR THIS CHAPTER
    You can find the wrox.com code downloads for this chapter at http://www.wiley.com/go/BeginningJavaScript5E on the Download Code tab. You can also view all of the examples and related files at http://beginningjs.com .
    One of the main uses of computers is to process and display information. By processing, we mean the information is modified, interpreted, or filtered in some way by the computer. For example, on an online banking website, a customer may request details of all money paid out from his account in the past month. Here the computer would retrieve the information, filter out any information not related to payments made in the past month, and then display what’s left in a web page. In some situations, information is processed without being displayed, and at other times, information is obtained directly without being processed. For example, in a banking environment, regular payments may be processed and transferred electronically without any human interaction or display.
    In computing, information is referred to as data. Data comes in all sorts of forms, such as numbers, text, dates, and times, to mention just a few. In this chapter, you look specifically at how JavaScript handles data such as numbers and text. An understanding of how data is handled is fundamental to any programming language.
    In this chapter you start by looking at the various types of data JavaScript can process. Then you look at how you can store this data in the computer’s memory so you can use it again and again in the code. Finally, you see how to use JavaScript to manipulate and process the data.

    TYPES OF DATA IN JAVASCRIPT

    Data can come in many different forms, or types
  • OCA Java SE 8 Programmer I Certification Guide
    primitive variable.
    Primitive data types, as the name suggests, are the simplest data types in a programming language. In the Java language, they’re predefined. The names of the primitive types are quite descriptive of the values that they can store. Java defines the following eight primitive data types:
    • char
    • byte
    • short
    • int
    • long
    • float
    • double
    • boolean
    Examine figure 2.1 and try to match the given value with the corresponding type.
    Figure 2.1. Matching a value with its corresponding type
    This should be a simple exercise. Table 2.1 provides the answers.
    Table 2.1. Matching a value with its corresponding data type
    Character values Integer values Decimal values Boolean
    a 100 7.3 true
      4573    
    In the preceding exercise, I categorized the data that you need to store as follows: character, integer, decimal, and Boolean values. This categorization will make your life simpler when confronted with selecting the most appropriate primitive data type to store a value. For example, to store an integer value, you need a primitive data type that’s capable of storing integer values; to store decimal numbers, you need a primitive data type that can store decimal numbers. Simple, isn’t it?
    Let’s map the types of data that the primitive data types can store, because it’s always easy to group and remember information.
    Note
    The category Boolean is not the same as the primitive data type boolean or wrapper class Boolean. Java primitive data types and class names are displayed using code font.
    The primitive data types can be categorized as follows: Boolean, character, and numeric (further categorized as integral and floating-point) types. Take a look at this categorization in figure 2.2 .
    Figure 2.2. Categorization of primitive data types
    As shown in figure 2.2 , the char primitive data type is an unsigned numeric data type. It can only store positive integers. The rest of the numeric data types (byte, short, int, long, float, and double) are signed numeric data types (they can store both negative and positive values). The categorization in figure 2.2
  • Professional JavaScript for Web Developers
    • Matt Frisbie(Author)
    • 2019(Publication Date)
    • Wrox
      (Publisher)
    5 Basic Reference Types

    WHAT'S IN THIS CHAPTER?

    • Working with objects
    • Understanding basic JavaScript data types
    • Working with primitives and primitive wrappers

    WROX.COM DOWNLOADS FOR THIS CHAPTER

    Please note that all the code examples for this chapter are available as a part of this chapter's code download on the book's website at www.wrox.com/go/projavascript4e on the Download Code tab.
    A reference value (object) is an instance of a specific reference type. In ECMAScript, reference types are structures used to group data and functionality together and are often incorrectly called classes. Although technically an object-oriented language, ECMAScript lacks some basic constructs that have traditionally been associated with object-oriented programming, including classes and interfaces. Reference types are also sometimes called object definitions because they describe the properties and methods that objects should have.
    NOTE   Even though reference types are similar to classes, the two concepts are not equivalent. To avoid any confusion, the term “class” is not used in the rest of this chapter.
    Again, objects are considered to be instances of a particular reference type. New objects are created by using the new operator followed by a constructor. A constructor is simply a function whose purpose is to create a new object. Consider the following line of code:
    let now = new Date();
    This code creates a new instance of the Date reference type and stores it in the variable now . The constructor being used is Date() , which creates a simple object with only the default properties and methods. ECMAScript provides a number of native reference types, such as Date , to help developers with common computing tasks.
    NOTE   Functions are a reference type, but they are too broad of a topic for this chapter and therefore have an entire chapter devoted to them. Refer to the Functions chapter.

    THE DATE TYPE

    The ECMAScript Date type is based on an early version of java.util.Date from Java. As such, the Date type stores dates as the number of milliseconds that have passed since midnight on January 1, 1970 UTC (Universal Time Code). Using this data storage format, the Date
  • Professional JavaScript for Web Developers
    • Nicholas C. Zakas(Author)
    • 2011(Publication Date)
    • Wrox
      (Publisher)
    Chapter 5 Reference Types WHAT’S IN THIS CHAPTER?
    • Working with objects
    • Creating and manipulating arrays
    • Understanding basic JavaScript data types
    • Working with primitives and primitive wrappers
    A reference value (object) is an instance of a specific reference type . In ECMAScript, reference types are structures used to group data and functionality together and are often incorrectly called classes . Although technically an object-oriented language, ECMAScript lacks some basic constructs that have traditionally been associated with object-oriented programming, including classes and interfaces. Reference types are also sometimes called object definitions , because they describe the properties and methods that objects should have.
    Even though reference types are similar to classes, the two concepts are not equivalent. To avoid any confusion, the term class is not used in the rest of this book.
    Again, objects are considered to be instances of a particular reference type. New objects are created by using the new operator followed by a constructor . A constructor is simply a function whose purpose is to create a new object. Consider the following line of code:
    var person = new Object();
    This code creates a new instance of the Object reference type and stores it in the variable person . The constructor being used is Object() , which creates a simple object with only the default properties and methods. ECMAScript provides a number of native reference types, such as Object , to help developers with common computing tasks.
    THE OBJECT TYPE
    Up to this point, most of the reference-value examples have used the Object type, which is one of the most often-used types in ECMAScript. Although instances of Object don’t have much functionality, they are ideally suited to storing and transmitting data around an application.
    There are two ways to explicitly create an instance of Object . The first is to use the new operator with the Object
  • Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.