DEV Community

Hariharan S J
Hariharan S J

Posted on

Understanding JavaScript Core Concepts: Spread Operator, Constructor Functions, and Built-in Objects

Spread Operator in JavaScript

Before technical part of spread operator we shall understand the spread operator by non technically

Imagine you have a bag of candies ๐Ÿฌ.

Inside the bag there are 3 candies:

[๐Ÿฌ, ๐Ÿฌ, ๐Ÿฌ]
Enter fullscreen mode Exit fullscreen mode

Now you want to pour all the candies out on the table.

When you open the bag and spread the candies on the table, that is like the Spread Operator (...) in JavaScript.

Simple Example

You have a box:

box1 = [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

Now you open the box and spread everything into another box

let box1 = [1,2,3];
let box2 = [...box1];
Enter fullscreen mode Exit fullscreen mode

Now box2 also has the same toys.

box2 = [1,2,3]
Enter fullscreen mode Exit fullscreen mode

Simple Meaning

Spread Operator (...) = Open a box and spread everything inside it.

Now lets deep dive into the technical part of spread operator

What is Spread Operator?

The Spread Operator (...) is used to expand (spread) the elements of an iterable (like an array or string) or the properties of an object into individual elements.

It was introduced in ES6 (ECMAScript 2015) and is commonly used for copying, merging, and passing values.

Basic Idea of Spread Operator

The spread operator takes a collection and spreads its values one by one

let arr = [10, 20, 30];

console.log(...arr);
Enter fullscreen mode Exit fullscreen mode

Output

10 20 30
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • arr is an array.

  • ...arr spreads the values inside the array

Instead of:

[10,20,30]
Enter fullscreen mode Exit fullscreen mode

It Becomes

10,20,30
Enter fullscreen mode Exit fullscreen mode

Spread Operator with Arrays

Copying an Array

Normally if you copy arrays like this

let a = [1,2,3];
let b = a;
Enter fullscreen mode Exit fullscreen mode

Both variables point to the same memory reference

So if you change b, a will also change

Using Spread

let a = [1,2,3];
let b = [...a];

b.push(4);

console.log(a); 
console.log(b);
Enter fullscreen mode Exit fullscreen mode

Output

[1,2,3]
[1,2,3,4]
Enter fullscreen mode Exit fullscreen mode

Explanation:

...a creates a new copy of the array

This is called Shallow Copy.

Merging Arrays

Spread operator is commonly used to combine multiple arrays

Example

let arr1 = [1,2];
let arr2 = [3,4];
let arr3 = [...arr1, ...arr2];

console.log(arr3);
Enter fullscreen mode Exit fullscreen mode

Output

[1,2,3,4]
Enter fullscreen mode Exit fullscreen mode

Here:

  • ...arr1 spreads 1,2

  • ...arr2 spreads 3,4

Final array becomes [1,2,3,4]

Adding Elements While Merging

You can also add new values.

let arr1 = [2,3];

let arr2 = [1, ...arr1, 4];

console.log(arr2);
Enter fullscreen mode Exit fullscreen mode

Output

[1,2,3,4]
Enter fullscreen mode Exit fullscreen mode

Spread operator does not have to be at the start.
It can be used anywhere in the array.

Spread Operator with Objects

Spread operator can also copy or merge objects

Example

let user = {name:"Hari"};
let details = {age:21};

let person = {...user, ...details};

console.log(person);
Enter fullscreen mode Exit fullscreen mode

Output

Explanation:

  • ...user spreads object properties

  • ...details spreads other properties

Result is a merged object

Spread Operator with Nested Arrays

Spread Operator with Nested Arrays

Example

let a = [[1,2],[3,4]];
let b = [...a];

b[0][0] = 100;

console.log(a);
Enter fullscreen mode Exit fullscreen mode

Output

[[100,2],[3,4]]
Enter fullscreen mode Exit fullscreen mode

Explanation

  • The inner arrays still share memory

Spread operator copies only the first level

Constructor Function In Javascript

before going into the technical part of constructor function lets all first understand it non technically

Imagine you have a toy machine ๐Ÿญ.

This machine can make many toy cars ๐Ÿš—.

You just press a button and tell the machine:

  • Color

  • Name

Then the machine creates a new toy car.

The Toy Machine = Constructor Function

In JavaScript, a constructor function is like that toy-making machine.

It helps us create many similar objects.

Now lets understand the constructor function concept technically

What is mean by constructor function in javascript?

A Constructor Function in JavaScript is a special type of function used to create and initialize objects. It acts as a blueprint (template) for creating multiple objects with similar properties and methods.

Constructor functions were the main way of creating objects before ES6 classes were introduced.

In Another words it can say as

A constructor function is simply a regular function that is used with the new keyword to create objects.

Example

function Person(name, age) {
  this.name = name;
  this.age = age;
}
Enter fullscreen mode Exit fullscreen mode

Here:

  • Person โ†’ constructor function

  • name, age โ†’ parameters

  • this โ†’ refers to the new object being created

Creating Objects Using Constructor

To create an object we use the new keyword

let user1 = new Person("Hari", 21);
let user2 = new Person("Surya", 25);

console.log(user1);
console.log(user2);
Enter fullscreen mode Exit fullscreen mode

Output

{ name: "Hari", age: 21 }
{ name: "Surya", age: 25 }
Enter fullscreen mode Exit fullscreen mode

Here we created two objects using the same constructor function.

What Happens Internally When new is Used

When we write:

let user = new Person("Hari",21);
Enter fullscreen mode Exit fullscreen mode

JavaScript performs 4 important steps internally.

Step 1 โ€” Create a new empty object

{}
Enter fullscreen mode Exit fullscreen mode

Step 2 โ€” Set this to the new object

Inside the function:

this โ†’ {}
Enter fullscreen mode Exit fullscreen mode

Step 3 โ€” Add properties to the object

this.name = "Hari"
this.age = 21
Enter fullscreen mode Exit fullscreen mode

Object becomes:

{ name:"Hari", age:21 }
Enter fullscreen mode Exit fullscreen mode

Step 4 โ€” Return the object

JavaScript automatically returns the new object.

Final Result

user = { name:"Hari", age:21 }
Enter fullscreen mode Exit fullscreen mode

Why this is Used in Constructor Functions

this refers to the object that is being created.

Example

function Car(brand) {
  this.brand = brand;
}

let car1 = new Car("Toyota");
let car2 = new Car("BMW");
Enter fullscreen mode Exit fullscreen mode

Objects Created

car1 โ†’ { brand: "Toyota" }
car2 โ†’ { brand: "BMW" }
Enter fullscreen mode Exit fullscreen mode

Here this.brand stores the value in each new object.

Problem if new is Not Used

Example:

function Person(name) {
  this.name = name;
}

let user = Person("Hari");

console.log(user);
Enter fullscreen mode Exit fullscreen mode

Output

undefined
Enter fullscreen mode Exit fullscreen mode

Because:

this refers to the global object, not a new object.

Constructor Naming Convention

Constructor functions usually start with a capital letter.

Example:

Person
User
Car
Student
Employee
Enter fullscreen mode Exit fullscreen mode

This is not mandatory but is a common JavaScript convention.

Using Prototype with Constructor Functions

To avoid copying methods for every object, we use prototype.

function Person(name) {
  this.name = name;
}

Person.prototype.sayHello = function() {
  console.log("Hello " + this.name);
};

let user1 = new Person("Hari");
let user2 = new Person("Surya");

user1.sayHello();
user2.sayHello();
Enter fullscreen mode Exit fullscreen mode

Now:

  • sayHello exists only once in memory

  • All objects share it

This improves memory efficiency.

Constructor Function Returning Values

Normally constructors return the object automatically.

But if you return another object manually:

function Test() {
  this.name = "Hari";

  return { age: 21 };
}

let obj = new Test();

console.log(obj);
Enter fullscreen mode Exit fullscreen mode

Output:

{ age: 21 }
Enter fullscreen mode Exit fullscreen mode

The returned object replaces the default object.

Advantages of Constructor Functions

  1. Create multiple objects easily

  2. Reusable object structure

  3. Works with prototypes

  4. Foundation for JavaScriptโ€™s object-oriented programming

Build In Objects In Javascript

before going into this topic we shall discuss this topic non technically

Imagine you have a magic calculator box ๐Ÿงฎโœจ.

This magic box can help you do many math things like:

  • finding the biggest number

  • finding the smallest number

  • rounding numbers

  • giving random numbers

  • finding square roots

In JavaScript, this magic box is called the Math Object.

Think Like This

Math = Magic Math Box
Enter fullscreen mode Exit fullscreen mode

Whenever you need help with math, you ask the box.

Example-Biggest Number

You ask the box:

Math.max(5, 10, 2)
Enter fullscreen mode Exit fullscreen mode

The Box Says

10
Enter fullscreen mode Exit fullscreen mode

Because 10 is the biggest.

Now lets deep dive in by technically

What is Mean By Json Object In Javascript

JSON stands for JavaScript Object Notation.
It is a lightweight data format used to store and exchange data between systems.

Even though it comes from JavaScript, JSON is now language-independent, meaning it can be used with:

  • JavaScript

  • Python

  • Java

  • PHP

  • C#

Why JSON Exists

Before JSON, systems used formats like XML to transfer data.

Example XML:

<user>
  <name>Hari</name>
  <age>21</age>
</user>
Enter fullscreen mode Exit fullscreen mode

This format is long and complex.

JSON solved this by being shorter and easier to read.

JSON Version:

{
  "name": "Hari",
  "age": 21
}
Enter fullscreen mode Exit fullscreen mode

JSON.stringify()

JSON.stringify() converts a JavaScript object into a JSON string.

Example:

let user = {
  name: "Hari",
  age: 21
};

let jsonData = JSON.stringify(user);

console.log(jsonData);
Enter fullscreen mode Exit fullscreen mode

Output:

{"name":"Hari","age":21}
Enter fullscreen mode Exit fullscreen mode

Conversion

JavaScript Object โ†’ JSON String

Enter fullscreen mode Exit fullscreen mode

JSON.parse()

JSON.parse() converts a JSON string into a JavaScript object.

Example:

let jsonData = '{"name":"Hari","age":21}';

let user = JSON.parse(jsonData);

console.log(user.name);
Enter fullscreen mode Exit fullscreen mode

Output:

Hari
Enter fullscreen mode Exit fullscreen mode

Conversion:

JSON String โ†’ JavaScript Object
Enter fullscreen mode Exit fullscreen mode

Math Object In Javascript.

The Math object in JavaScript is a built-in global object that provides mathematical constants and functions for performing calculations.

Important point:

The Math object is not a constructor, so we do not use new Math().

Why the Math Object Exists

Programming often requires mathematical operations like:

1.rounding numbers

2.finding maximum or minimum values

3.generating random numbers

4.trigonometric calculations

5.powers and square roots

Instead of writing these algorithms manually, JavaScript provides the Math object with built-in methods.

Math Methods

Math.max()

Returns the largest value

Math.max(10, 50, 20)
Enter fullscreen mode Exit fullscreen mode

Output

50
Enter fullscreen mode Exit fullscreen mode

Internally it compares numbers and returns the maximum.

Math.round()

Rounds a number to the nearest integer.

Math.round(4.6)
Enter fullscreen mode Exit fullscreen mode

Output

5
Enter fullscreen mode Exit fullscreen mode

Rules:

0.5 or greater โ†’ round up
less than 0.5 โ†’ round down
Enter fullscreen mode Exit fullscreen mode

Example:

Math.round(4.4) โ†’ 4
Math.round(4.5) โ†’ 5
Enter fullscreen mode Exit fullscreen mode

Math.floor()

Rounds down to the nearest integer.

Math.floor(4.9)
Enter fullscreen mode Exit fullscreen mode

Output

4
Enter fullscreen mode Exit fullscreen mode

Example:

Math.floor(8.99) โ†’ 8
Math.floor(3.1) โ†’ 3
Enter fullscreen mode Exit fullscreen mode

Math.trunc()

Removes the decimal part.

Math.trunc(5.9)
Enter fullscreen mode Exit fullscreen mode

Output:

5
Enter fullscreen mode Exit fullscreen mode

Math.sqrt()

Calculates square root.

Math.sqrt(625)
Enter fullscreen mode Exit fullscreen mode

Output

25
Enter fullscreen mode Exit fullscreen mode

Math.crbt()

Calculates Cube root.

Math.cbrt(27)
Enter fullscreen mode Exit fullscreen mode

Output

3
Enter fullscreen mode Exit fullscreen mode

Top comments (0)