Flat Preloader Icon

JS Object

JavaScript objects are fundamental data structures in the language, used to store collections of key-value pairs. They are versatile and can represent complex data in a structured way.

The Number Object

  • The Number object in JavaScript is a global object that represents numerical values. It’s one of the seven built-in data types in JavaScript and can represent both integer and floating-point numbers.

1. Creating Number Objects:

  • You can create a Number object using the Number() constructor function:
				
					const num = new Number(42);

				
			

Or you can simply use the primitive number literals:

				
					const num = 42;

				
			

2. Properties of Number Object:

  • Number.MAX_VALUE: Returns the largest representable number in JavaScript.
  • Number.MIN_VALUE: Returns the smallest positive representable number in JavaScript.
  • Number.NaN: Represents “Not-A-Number” value.
  • Number.NEGATIVE_INFINITY: Represents negative infinity.
  • Number.POSITIVE_INFINITY: Represents positive infinity.

Object Literal:

An object literal is a comma-separated list of name-value pairs wrapped in curly braces {}. It’s a convenient way to create a single instance of an object.

				
					const person = {
    name: "John",
    age: 30,
    city: "New York"
};

				
			

Object Constructor:

JavaScript provides a built-in constructor function Object() to create objects.

				
					const car = new Object();
car.make = "Toyota";
car.model = "Camry";

				
			

Properties:

Objects can have properties, which are essentially key-value pairs. Properties can be primitive data types like strings, numbers, or booleans, as well as objects or functions.

				
					console.log(person.name); // Accessing property 
using dot notation
console.log(car["make"]); // Accessing property
using bracket notation

				
			

Methods:

Properties can also hold functions, which are referred to as methods.

				
					const calculator = {
    add: function(x, y) {
        return x + y;
    },
    subtract: function(x, y) {
        return x - y;
    }
};

console.log(calculator.add(5, 3));
// Outputs: 8

				
			

The this Keyword

  • In a function definition, this refers to the “owner” of the function.
  • In the example above, this is the person object that “owns” the fullName function.

  • In other words, this.firstName means the firstName property of this object.