JavaScript Primitive and Non Primitive Data Types with Examples

JavaScript Primitive and Non Primitive Data Types with Examples

In JavaScript, there are several data types, including primitive and non-primitive (object) types; In this tutorial, we will show you JavaScript primitive and non-primitive (object) data types and their unique characteristics with examples.

JavaScript Data Types with Examples

In JavaScript, data types can be broadly categorized into two main groups: primitive data types and non-primitive data types:

Primitive Data Types in JavaScript

Primitive data types are the simplest forms of data and can hold only one value each. JavaScript has six premitive data types, which are

  1. undefined
  2. null
  3. number
  4. string
  5. boolean
  6. symbol

Non-primitive Data Types in JavaScript

Non-Primitive data types are complex forms of data and can hold multiple values. JavaScript has two non-premitive data types, which are

  1. object
  2. array
  3. function

Now, Let’s discuss primitive data types in detail:

1. The undefined type

The undefined  data type in JavaScript represents a variable that has been declared but not assigned a value.

Note:- Meaning of undefined is “value is not assigned”.

Explore this example for clarification:

let foo;
console.log(foo);        // undefined
console.log(typeof foo); // undefined

In this example,foo is a variable. Since foo is not declared, it is not assigned the value. The type of foo is also undefined.

When you print a variable, which value is not assigned. So  typeof operator also returns undefined.

Explore this example for clarification:

console.log(typeof bar); // undefined

2. The null type

The null data type in javascript represents a value of a variable that is empty or undefined.

Take a look at this illustrative example:

let obj = null;
console.log(typeof obj); // object

Take next example for practice. Define a variable and assign a variable  null value. So that ,you can check whether the variable is null or not by using the if-else statement.

Take a look at this illustrative example:

let obj = null;
if(obj != null) {
   // call method
}else{
   // call different methods
}

JavaScript defines that null is equal to undefined as shown in the following statement.

console.log(null == undefined); // true

3. The number type

The number data type holds numeric values, such as 1, 2, 3, and -8. The values are integer and floating points.

Many operations can be done with numbers e.g. multiplication *, division /, addition +, subtraction -, and so on.

Integer numbers

The following statement declares a variable that contains an integer.

let num = 100;

If you want to represent the octal (base 8) literals, you put the first digit as zero (0) followed by octal digit numbers (0 to 7) as follows:

let oct = 060; // octal for 48

If the literal of an octal number is out of the range, JavaScript treats it as a decimal as shown in the following example.

let d = 090; // intepreted as 90

To avoid the confusion, ES6 allows you to specify an octal literal by using the prefix 0o followed by a sequence of octal digits from 0 through 7:

let v = 0o45;
console.log(v); // 37

To create hexadecimal (base 16) literal, you must use 0x (in lowercase) as the first two characters followed by any number of hexadecimal digits (0 to 9, and A to F).

let h = 0xf; // same as 0xF hexadecimal for 15

Floating-point numbers

To represent a floating-point number in js, include a decimal point with number.

Take a look at this illustrative example:

let f1 = 16.4; 
let f2 = .5;   // same as 0.5, also valid but not recommended

JavaScript converts a floating-point number into an integer number if the number appears to be the whole number. The reason is that Javascript always wants to use less memory since a floating-point value uses twice as much memory as an integer value.

let f3 = 500.00; // interpreted as integer 500

JavaScript allows you to use the e-notation to represent very large or small numbers as in the following example.

let f4 = 3.17e6; // ~ 3170000

JavaScript provides the minimum and maximum values of a number that you can access using Number.MIN_VALUE and Number.MAX_VALUE. In addition, JavaScript uses Infinity and -Infinity to represent the finite numbers, both positive and negative.

See the following example:

console.log(Number.MAX_VALUE); // 1.7976931348623157e+308
console.log(Number.MIN_VALUE); // 5e-324
console.log(Number.MAX_VALUE + Number.MAX_VALUE); // Infinity
console.log(-Number.MAX_VALUE - Number.MAX_VALUE); // -Infinity

NaN

JavaScript has a special numeric value called NaN, which stands for Not a Number. In fact, it means an invalid number.

Explore this example for clarification:

here, division of a string by a number returns NaN as in the following example.

console.log('a'/2); // NaN;

The NaN has two special characteristics:

  1. Any operation with NaN returns NaN.
  2. The NaN does not equal any value, including itself.

Take a look at this illustrative example:

console.log(NaN/2); // NaN
console.log(NaN == NaN); // false

4. The string type

The string data type stores text values, such as “Hello, world!” and “This is a string”. It must be enclosed in single or double quotation marks.

Take a look at this illustrative example:

let greeting = 'Hi';
let foo = "It's a valid string";
let bar = 'I'm also a string';

JavaScript strings are immutable. It means that you cannot modify a string once it is created. However, you can create a new string based on an operation on the original string, like this:

let myStr = 'js';
myStr = myStr + ' world';

In this example:

  • First, declare the myStr variable and initialize it to a string of 'js'.
  • Second, use the + operator to combine 'js' with ' world' to make its value as 'js world'.

Behind the scene, JavaScript engine creates a new string that holds the new string 'js world' and destroys two other original strings 'js' and ' world'.

5. The boolean type

The boolean datatype variable holds only one value, which can be true or false, in lowercase.

Explore this example for clarification:

Declares two variables that hold boolean values.

let a = true;
let b = false;
console.log(typeof b); // boolean

JavaScript allows values of other types to be converted into boolean values of true or false.

To convert a value of another data type into a boolean value, you use the Boolean function. The following table shows the conversion rules:

Typetruefalse
stringnon-empty stringempty string
numbernon-zero number and Infinity0, NaN
objectnon-null objectnull
undefinedundefined

See the following demonstration.

console.log(Boolean('Hi'));// true
console.log(Boolean(''));  // false
console.log(Boolean(20));  // true
console.log(Boolean(Infinity));  // true
console.log(Boolean(0));  // false
console.log(Boolean({foo: 100}));  // true on non-empty object
console.log(Boolean(null));// false

6. The symbol type

JavaScript added a primitive type in ES6: the symbol. Different from other primitive types, the symbol type does not have a literal form.

To create a symbol, you call the Symbol function as follows:

let s1 = Symbol();

Note that Symbol is a function, not an object constructor, therefore, you cannot use the new operator. If you do so, you will get a TypeError.

The Symbol function creates a new unique value every time you call it.

console.log(Symbol() == Symbol()); // false

You can pass a descriptive string to the Symbol function for the logging and debugging purposes.

let s2 = Symbol('event.save');

When you call the toString() method on the symbol variable, it returns more descriptive name as shown below:

console.log(s2.toString()); // Symbol(event.save)

You can use symbols for many purposes. One of them is to create a string-like constant that can’t clash with any other value. The following example creates a symbol that represents the click event.

const click = Symbol('click');

The string 'click' may be used for different purposes and not unique. However, the click symbol is absolutely unique.

Now, Let’s discuss non primitive data types in detail:

1. The object type

In JavaScript, an object is a collection of properties, where each property is defined as a key-value pair.

The following example defines an empty object using the object literal form:

var emptyObject = {};

The following example defines the ps object with two properties:

var ps = {
    firstName: 'John',
    lastName: 'Doe'
};

A property name of an object can by any string. You can use quotes around the property name if it is not valid JavaScript identifier.

For example, if you have a property first-name, you must use the quotes such as "first-name" but firstName is a valid JavaScript identifier so the quotes are optional.

If you have more than one property, you use a comma ( ,) to separate the pairs.

JavaScript allows you to nest object as shown in the following example:

var contact = {
    firstName: 'John',
    lastName: 'Doe',
    email: '[email protected]',
    phone: '(408)-555-9999',
    address: {
        building: '4000',
        street: 'North 1st street',
        city: 'San Jose',
        state: 'CA',
        country: 'USA'
    }
}

The contact object consists of firstNamelastNameemailphone, and address properties. The address property itself is also an object that consists of building,  streetcitystate, and country properties.

You can access the properties of an object by using two notations: the dot notation (.) and array-like notation ( []).

The following example uses the dot notation (.) to access the firstName and lastName properties of the contact object.

console.log(contact.firstName);
console.log(contact.lastName);

To get property of a nested object, you use the following form:

console.log(contact.address.country);

If you refer to a non-existent property, you will get an undefined value as follows:

console.log(contact.age); // undefined

The following example uses the array-like notation to access the email and phone properties of the contact object.

console.log(contact['phone']); // '(408)-555-9999'
console.log(contact['email']); // '[email protected]'

Besides the object literal form, you can use the new keyword to create a new object as follows:

let customer = new Object();

And assign the property of the object a value:

customer.name = 'ABC Inc.';

In JavaScript, all objects are derived from the Object type. We will discuss more the Object type in the next tutorial.

2. The Array Data Type

An array is a non-primitive data type in js, which is used to store multiple values in a single variable. Each elements an array has a numeric position, known as its index. Using the index, can access values from an array.

The following example defines an array with values:

let colors = ["Red", "Yellow", "Green", "Orange"]; 

The following example access values from an array:

console.log(color[0]) // Red

3. The Function Data Type

In JavaScript, a function allows one to define a block of code, give it a name, and then execute it as many times. So it is possible to assign them to variables.

Explore this example for clarification:

The following example defines a function named say that has a return value “Hello World”.

var say = function(){ 
    return "Hello World!"; 
}
 
// Check the type of greeting variable
console.log(typeof say) // Output: function
console.log(say());     // Output: Hello World!

The typeof Operator

JavaScript is a dynamic language or loosely typed so a variable is not associated with any type, however, its value is. In other words, the same variable can hold values ​​of different types at any given time.

If you want to check any variable Data Types at runtime in javascript, you can use the  typeof operator.

The typeof operator can be used to determine type of variable or operand. It can be used with or without parentheses (typeof(x) or typeof x).

Take a look at this illustrative example:

 
// Undefined
typeof undefined;  // Returns: "undefined"
typeof undeclaredVariable; // Returns: "undefined"
 
// Null
typeof Null;  // Returns: "object"
// Booleans
typeof true;  // Returns: "boolean"
typeof false;  // Returns: "boolean"
// Numbers
typeof 15;  // Returns: "number"
typeof 42.7;  // Returns: "number"
typeof 2.5e-4;  // Returns: "number"
typeof Infinity;  // Returns: "number"
typeof NaN;  // Returns: "number". Despite being "Not-A-Number"
 
// Strings
typeof '';  // Returns: "string"
typeof 'hello';  // Returns: "string"
typeof '12';  // Returns: "string". Number within quotes is typeof string
 
// Objects
typeof {name: "John", age: 18};  // Returns: "object"
 
// Arrays
typeof [1, 2, 4];  // Returns: "object"
 
// Functions
typeof function(){};  // Returns: "function

Conclusion

In this tutorial, you have learned javascript primitive and non-primitive data types including undefined, null, number, string, boolean, symbol, object, date, and array.

Recommended JavaScript Tutorial

Recommended:-JavaScript Arrays

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *