JavaScript Data Types

JavaScript Data Types

Hey folks, what's up? Today I'm going to write about DataTypes in javascript. As we know JavaScript is a versatile Dynamically typed language. In JavaScript, data types are divided into two main categories: primitive types and non-primitive types (objects). Understanding these data types is fundamental to writing effective JavaScript code.

Primitive Data Types

Primitive data types are immutable, meaning they cannot be altered once they are declared.

let str = 'Hello';
str[0] = 'Y';
console.log(str); // Hello
  1. Number

    • Represents both integer and floating-point numbers.

    • Example

let num1 = 42; // integer
let num2 = 3.14; //floating point
  1. String
  • Represents a sequence of characters.

  • Strings can be created using single quotes ('), double quotes ("), or backticks (`) for template literals.

  • Examples:

let str1 = 'Hello';
let str2 = "World";
let str3 = `Hello, ${str2}!`; // Template literal
  1. Boolean
  • Represents a logical entity and can have two values: true or false.

  • Example:

let isTrue = true;
let isFalse = false;
  1. Undefined
  • Represents a variable that has been declared but not yet assigned a value.

  • Example:

let x;
console.log(x); // undefined
  1. Null
  • Represents the intentional absence of any object value.

  • Represents an empty value.

let y = null;
console.log(y); // null
  1. Symbol (introduced in ES6)
  • Represents a unique and immutable primitive value, often used to create unique identifiers for object properties.

  • Introduced in ECMAScript 6.

const sym1 = Symbol('foo');
const sym2 = Symbol('foo');
console.log(sym1 === sym2); // false
console.log(sym1 == sym2); // false
  1. BigInt
  • Represents an arbitrary-precision integer.

  • Introduced in ECMAScript 11.

let bigInt = 1234567890123456789012345678901234567890n;

Non-Primitive Data Types (Objects)

Non-primitive data types are mutable, meaning that their values can be changed after they are declared.

let arr = ['Apple', 'Banana', 'Cherry'];
arr[0] = 'Orange';
console.log(arr); // ['Orange', 'Banana', 'Cherry']
  1. Object

    • Represents a collection of properties, where each property is a key-value pair.

    • Example:

let person = {
    name: 'John',
    age: 30,
    greet: function() {
        console.log('Hello');
    }
};
console.log(person.name); // John
person.greet(); // Hello
  1. Array
  • A special type of object is used to store ordered collections of values.

  • Represents a list of elements.

  • Example:

let fruits = ['Apple', 'Banana', 'Cherry'];
console.log(fruits[0]); // Apple
  1. Function

    • A callable object that executes a block of code.

    • Example:

function add(a, b) {
    return a + b;
}
console.log(add(2, 3)); // Outputs:
  1. Date

    • Represents date and time.

    • Example:

let today = new Date();
console.log(today); // Outputs: current date and time
  1. RegExp
  • Represents regular expressions, which are used for pattern matching within strings.

  • Example:

let re = /ab+c/;
console.log(re.test('abbbc')); // true

Explanation:

Regular expression patterns are enclosed within forward slashes (/). The pattern ab+c consists of three parts:

Let's apply the regular expression /ab+c/ to the string 'abbbc': First Character 'a': The string contains the character 'a', which matches the first part of the pattern.

One or More 'b's: The string contains three 'b's ('bbb'), which satisfies the b+ part of the pattern (one or more 'b's).

Last Character 'c': The string ends with the character 'c', which matches the last part of the pattern.

  • The string contains the character 'a', which matches the first part of the pattern.

  • One or More 'b's: The string contains three 'b's ('bbb'), which satisfies the b+ part of the pattern (one or more 'b's).

  • Last Character 'c': The string ends with the character 'c', which matches the last part of the pattern.

  1. Map
  • Represents a collection of key-value pairs.
let map = new Map();
map.set('name', 'John');
map.set('age', 30);
console.log(map.get('name')); // John
  1. Set
  • Represents a collection of unique values.

  • Example:

let set = new Set();
set.add(1);
set.add(2);
set.add(1);
console.log(set.size); // 2
  1. ArrayBuffer
  • Represents a fixed-length raw binary data buffer.

  • Example:

let buffer = new ArrayBuffer(16);
console.log(buffer.byteLength); // 16
  1. DataView
  • Provides a low-level interface for reading and writing multiple number types in an ArrayBuffer.

  • Example:

let view = new DataView(buffer);
view.setInt8(0, 42);
console.log(view.getInt8(0)); // 42

Special Values

  1. Infinity

    • Represents mathematical infinity.

    • Example:

console.log(1 / 0); // Infinity
  1. NaN (Not-a-Number)
  • Represents a value that is not a legal number.

  • Example:

console.log(0 / 0); // NaN
console.log(Math.sqrt(-1)); // Outputs: NaN

Type Conversion

JavaScript provides functions for converting values from one type to another. Two types of Type Conversion: Implicit and Explicit Type Conversion.

Implicit Type Conversion:

JavaScript automatically converts the data type of a value to another data type.

let num = 42;
let strs = 'The answer is ' + num;
console.log(strs); // The answer is 42

Explicit Type Conversion:

JavaScript provide various methods for explicitly converting a value to specific data type.

  1. Number Conversion
  • Using Number() function or parseInt(), parseFloat().

  • Convert a value to a number.

  • Example:

let x1 = '42';
let y1 = Number(x);
console.log(y1); // 42
  1. String Conversion
  • Using String() function or toString() method.

  • Convert a value to a string.

  • Example:

let x2 = 42;
let y2 = String(x);
console.log(y2); // '42'
  1. Boolean Conversion
  • Using Boolean() function.

  • Convert a value to a boolean.

  • Example:

let x3 = 42;
let y3 = Boolean(x);
console.log(y3); // true

Type Checking

  1. typeofOperator

    • Return the data type of a variable.
console.log(typeof 42); // number
console.log(typeof 'Hello'); // string
console.log(typeof true); // boolean
console.log(typeof undefined); // undefined
console.log(typeof null); // object (this is a known quirk in JavaScript)
console.log(typeof Symbol('foo')); // symbol
console.log(typeof 1234567890123456789012345678901234567890n); // bigint
console.log(typeof {}); // object
console.log(typeof []); // object
console.log(typeof function() {}); // function
console.log(typeof new Date()); // object
console.log(typeof /ab+c/); // object
console.log(typeof new Map()); // object
console.log(typeof new Set()); // object
console.log(typeof new ArrayBuffer(16)); // object
console.log(typeof new DataView(new ArrayBuffer(16))); // object

Key Points:

  • Dynamic Typing: JavaScript is dynamically typed, meaning variables can hold values of any type without type declarations.

  • Type Conversion: JavaScript performs implicit type conversion in many situations, which can lead to unexpected results. It's essential to be aware of this behaviour to avoid bugs.

  • Strict Equality (===) vs. Loose Equality (==): Strict equality checks both value and type, while loose equality performs type conversion before comparison.

Practical Tips:

  • Use typeof to check the type of a variable.

  • Prefer === over == to avoid type coercion issues.

  • Use let and const for variable declarations to reduce scope-related errors and improve code readability.

  • Understand and use the appropriate data type for your operations to ensure efficient and bug-free code.

Conclusion

JavaScript is a versatile and dynamic programming language that offers a variety of data types to handle different kinds of information. Understanding these data types is crucial for effective programming and avoiding common pitfalls. This summary encapsulates the key aspects of JavaScript data types, emphasizing the importance of understanding and correctly utilizing them for effective programming.

Happy Learning