Tuesday, 29 October 2024

JavaScript Data Types: A Beginner Guide with Examples

JavaScript is a dynamically typed language, which means that variables can hold different types of values at different times. JavaScript has several built-in data types, which are broadly categorized into two main groups:

1.   primitive and

2.   reference (or object) types.

 

1. Primitive Data Types

Primitive data types are the most basic types of data. Following section talks more about the primitive types.

 

1.1 Number

The Number type represents both integer and floating-point numbers. JavaScript doesn’t differentiate between integers and floating-point numbers; they are all of the type Number.

 

Example

let integer = 42;            // Integer
let float = 3.14;            // Floating-point number
let negative = -10;          // Negative number
let exponent = 2.5e3;        // Exponent (2.5 * 10^3 = 2500)
let notANumber = NaN;        // Special value representing Not-a-Number
let infinity = Infinity;     // Represents positive infinity
let negInfinity = -Infinity; // Represents negative infinity

 

a.   NaN is returned when a mathematical operation fails (e.g., dividing 0 by 0), or the final mathematical result is not a number.

b.   Infinity and -Infinity represent the result of a mathematical operation that exceeds the range of numbers representable in JavaScript.

 

1.2 String

The String type represents a sequence of characters. Strings are enclosed in single quotes (' '), double quotes (" "), or backticks (` `).

 

Example

let singleQuotes = 'Hello';
let doubleQuotes = "World";
let templateLiteral = `Hello, ${singleQuotes} ${doubleQuotes}!`;

 

Template literals (enclosed by backticks) allow embedded expressions (${expression}) and can span multiple lines.

 

1.3 Boolean

The Boolean type has only two possible values: true or false.

let isJavaScriptFun = true;
let isCodingHard = false;

 

Booleans are often used in conditional testing to determine the flow of control (e.g., if, else, while).

 

1.4 Undefined

A variable that has been declared but has not been assigned a value has the type undefined.

 

Example

let uninitializedVar;
console.log(uninitializedVar); // Output: undefined

‘undefined’ is the default value of a declared but unassigned variable.

 

1.5 Null

The null type represents the intentional absence of any object value. It is one of JavaScript’s primitive values.

let emptyVar = null;

‘null’ is often used to indicate that a variable is empty or should have no value.

 

1.6 Symbol

Introduced in ECMAScript 2015 (ES6), Symbol is a unique and immutable primitive value, typically used as an identifier for object properties.

 

Example

let sym1 = Symbol('description');
let sym2 = Symbol('description');
console.log(sym1 === sym2); // Output: false

Even though sym1 and sym2 have the same description, they are unique and not equal.

 

1.7 BigInt

BigInt is used to represent integers with arbitrary precision. This is useful for working with numbers larger than Number.MAX_SAFE_INTEGER.

 

Example

let bigIntNum = BigInt(9007199254740991) + BigInt(1);
console.log(bigIntNum); // Output: 9007199254740992n

BigInts are created by appending n to the end of an integer or by using the BigInt constructor.

 

2. Reference Data Types (Objects)

Reference types are objects that are instances of classes or can be used to represent collections of data.

 

2.1 Object

An Object is a collection of key-value pairs, where keys are strings (or symbols) and values can be any type.

 

Example

let person = {
    name: "John",
    age: 30,
    isDeveloper: true,
    sayHello: function() {
        console.log("Hello!");
    }
};
console.log(person.name); // Output: John
person.sayHello();        // Output: Hello!

Objects can have methods (functions) and properties (values).

 

2.2 Array

An Array is a special type of object used to store an ordered list of values, which can be of any type.

 

array.js

let numbers = [1, 2, 3, 4, 5];
console.log(numbers[0]); // Output: 1

Arrays are zero-indexed, meaning the first element is accessed with index 0.

 

2.3 Function

A Function is a reusable block of code designed to perform a particular task. Functions are objects in JavaScript.

 

functions.js

function add(a, b) {
    return a + b;
}
console.log(add(2, 3)); // Output: 5

Functions can take arguments and return a value. They can also be assigned to variables.

 

2.4 Date

Date objects represent a single moment in time.

 

dateDemo.js

let now = new Date();
console.log(now); // Output: Current date and time

Date objects are created using the new Date() constructor and can be manipulated to get various time-related values.

 

2.5 RegExp

RegExp objects are used for pattern matching in strings.

 

Example

let pattern = /hello/i;
console.log(pattern.test("Hello world")); // Output: true

Regular expressions are used to perform complex string searches and manipulations.

 

Type Coercion or Type Conversion

JavaScript performs automatic type conversion (type coercion) when needed.

 

Example

console.log("5" + 2);  // Output: "52" (string concatenation)
console.log("5" - 2);  // Output: 3 (string converted to number)

Type Checking

typeof is used to check the type of a variable.

 

Example

console.log(typeof 42);          // Output: "number"
console.log(typeof "Hello");     // Output: "string"
console.log(typeof true);        // Output: "boolean"
console.log(typeof undefined);   // Output: "undefined"
console.log(typeof null);        // Output: "object" (this is a known quirk in JavaScript)
console.log(typeof {});          // Output: "object"
console.log(typeof []);          // Output: "object"
console.log(typeof function(){});// Output: "function"

 

JavaScript has a rich set of data types, each serving a specific purpose. Understanding these types is fundamental to writing efficient and effective JavaScript code.

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment