JavaScript Data Types, Objects and Prototypes

JavaScript Data Types

In JavaScript, data types categorize the values that variables can hold. Understanding these data types is fundamental to programming in JavaScript. There are two categories of data types in JavaScript: primitive and non-primitive.

JavaScript Data Types


Primitive Data Types

Primitive data types are the most basic data types in JavaScript. They include:

  1. Number: Represents numeric values, e.g., 123, 120.50 etc.
  2. BigInt: This data type can store larger integers than the Number type.
  3. String: Represents a sequence of characters, e.g., "hello". Strings in JavaScript are immutable.
  4. Boolean: Represents a logical entity and can have two values: true or false.
  5. Null: This type has one value: null.
  6. Undefined: A variable that has not been assigned a value is of type undefined.
  7. Symbol: This data type was introduced in ES6, and it is used to create anonymous property names.

Here’s an example of declaring these data types:

let num = 123; // Number
let bigInt = 123n; // BigInt
let str = "Hello, World!"; // String
let bool = true; // Boolean
let nothing = null; // Null
let undef; // Undefined
let sym = Symbol("sym"); // Symbol

Non-Primitive Data Type

Non-primitive data types are not data structures, and they are used to store multiple values. In JavaScript, the non-primitive data type is the Object. The Object data type is used to store collections of data.

let person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

In this example, person is an object with properties firstName, lastName, age, and eyeColor.

In conclusion, understanding data types in JavaScript is crucial for manipulating variables and creating efficient code. Whether you’re dealing with numbers, strings, or objects, JavaScript offers a variety of data types to fit your needs.

JavaScript Objects

In JavaScript, an object is a standalone entity with properties and types. It’s similar to real-world objects like a pen, which has properties like color, design, and material. In JavaScript, objects are a collection of key-value pairs, where each key maps to a value.

Creating Objects

There are several ways to create objects in JavaScript:

  1. Object Literals: This is the simplest way to create a JavaScript object.
let car = {
  make: 'Toyota',
  model: 'Camry',
  year: 2020
};
  1. Constructor Function: You can define a constructor function and then create an object using the new keyword.
function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}

let car = new Car('Toyota', 'Camry', 2020);
  1. Object.create() Method: This method creates a new object using an existing object as the prototype of the newly created object.
let car = Object.create(Object.prototype, {
  make: {
    value: 'Toyota',
    enumerable: true
  },
  model: {
    value: 'Camry',
    enumerable: true
  },
  year: {
    value: 2020,
    enumerable: true
  }
});

Accessing Object Properties

You can access the properties of an object using dot notation or bracket notation.

console.log(car.make); // Outputs: Toyota
console.log(car['model']); // Outputs: Camry

Modifying Objects

You can add, modify, or delete properties of an object.

car.color = 'Red'; // Adds a new property
car.make = 'Honda'; // Modifies the value of a property
delete car.year; // Deletes a property

In conclusion, JavaScript objects are a fundamental part of the language and understanding them is crucial for writing efficient and maintainable code. They provide a way to group related data and functions together, making your code more organized and easier to understand.

JavaScript Built-In Objects

JavaScript, a high-level, interpreted programming language, is renowned for its versatility and ubiquity in web development. One of its powerful features is the availability of built-in objects, also known as global objects. These objects, integral to the language specification, provide a plethora of functionalities accessible at the global scope. Let’s delve into some of these objects:

Number

The Number object wraps numeric values. It provides properties for numerical constants, such as MAX_VALUE, MIN_VALUE, and methods for numerical operations.

let num = new Number(12345.6789);
console.log(num.toFixed(2)); // Outputs: 12345.68

Math

The Math object offers a set of mathematical constants and functions. It’s a static object, so you use it directly rather than creating instances of it.

console.log(Math.PI); // Outputs: 3.141592653589793
console.log(Math.sqrt(16)); // Outputs: 4

Date

The Date object is used to work with dates and times. Date objects are created with the new Date() constructor.

let date = new Date();
console.log(date); // Outputs current date and time

String

The String object is a wrapper around the string primitive data type. It provides methods to manipulate strings.

let str = new String("Hello, World!");
console.log(str.length); // Outputs: 13

Error

The Error object provides a built-in error type. It can be used as a base object for user-defined exceptions.

throw new Error('This is an error message');

Function

The Function constructor creates a new Function object. In JavaScript, every function is actually a Function object.

let func = new Function('a', 'b', 'return a * b');
console.log(func(4, 3)); // Outputs: 12

Boolean

The Boolean object is a wrapper around the boolean primitive data type.

let bool = new Boolean(false);
console.log(bool); // Outputs: false

In conclusion, JavaScript’s built-in objects extend the capabilities of the language, providing developers with robust tools to create dynamic and interactive web applications. Understanding these objects is fundamental to mastering JavaScript.

Prototypes and Prototypal Inheritance in JavaScript

JavaScript, unlike classical object-oriented languages, is built around a prototype-based model. This model forms the core of object-oriented programming (OOP) in JavaScript.

What is a Prototype?

In JavaScript, a prototype is an object from which another object inherits properties. Every object in JavaScript has a prototype, except for the base object (the end of the prototype chain), which has a prototype of null.

Prototypal Inheritance

Prototypal inheritance is a feature in JavaScript used to add methods and properties to objects. It is a method by which an object can inherit the properties and methods of another object. This is achieved through the prototype chain. If you try to access a property that does not exist in the object, JavaScript will look up the prototype chain until it either finds the requested property or reaches an object with a null prototype.

Here’s a simple example:

let animal = {
  eats: true
};

let rabbit = {
  jumps: true,
  __proto__: animal
};

console.log(rabbit.eats); // Outputs: true

In this example, rabbit inherits the eats property from the animal object.

Object.getPrototypeOf and Object.setPrototypeOf

Traditionally, in order to get and set the prototype of an object, we use Object.getPrototypeOf and Object.setPrototypeOf.

let animal = {
  eats: true
};

let rabbit = {
  jumps: true
};

Object.setPrototypeOf(rabbit, animal);

console.log(Object.getPrototypeOf(rabbit) === animal); // Outputs: true
console.log(rabbit.eats); // Outputs: true

In this example, we first set the prototype of rabbit to be animal using Object.setPrototypeOf. Then we verify this by checking if the prototype of rabbit is animal using Object.getPrototypeOf.

In conclusion, understanding prototypes and prototypal inheritance is fundamental to mastering JavaScript and its object-oriented features. They provide a way to easily define shared properties and methods, which can be inherited by other objects. This leads to more efficient code reuse and a more manageable codebase.

Comments

Popular posts from this blog

GTM for SFCC

Java Interview Questions

Javascript check if key exists in map