While learning JavaScript objects, I came across constructors and arrays.
Both sounded a little confusing at first, but after using them, they became much easier to understand.
Constructors
A constructor is useful when we want to create multiple objects with the same structure.
For example, if we want to create multiple users, we don't have to write the same object again and again.
function User(name, age) {
this.name = name;
this.age = age;
}
Now we can create users using new.
const user1 = new User("John", 22);
We can create more users using the same constructor.
In modern JavaScript, we can also use a class with a constructor:
class User {
constructor(name) {
this.name = name;
}
}
The basic idea is simple: constructors help us create similar objects easily.
Arrays
Arrays are used when we want to store multiple values in one place.
const fruits = ["Apple", "Mango", "Orange"];
Array indexes start from 0, so fruits[0] gives us "Apple".
There are many array methods in JavaScript. Here are some basic ones I found useful.
length
length tells us how many items are in the array.
console.log(fruits.length);
toString()
It converts the array into a string.
console.log(fruits.toString());
at()
It returns an item at a particular position.
console.log(fruits.at(1));
join()
It joins the array elements using the separator we provide.
console.log(fruits.join(" - "));
push()
It adds an item to the end of the array.
fruits.push("Banana");
pop()
It removes the last item.
fruits.pop();
shift()
It removes the first item.
fruits.shift();
unshift()
It adds an item to the beginning.
fruits.unshift("Grapes");
concat()
It can be used to combine arrays.
let more = fruits.concat(["Kiwi"]);
slice()
It returns a part of an array without changing the original array.
let result = fruits.slice(0, 2);
splice()
It can be used to add, remove, or replace items in an array.
fruits.splice(1, 1);
flat()
It is useful when an array contains other arrays and we want to flatten them.
let nums = [1, [2, 3]];
console.log(nums.flat());
isArray()
It checks whether a value is actually an array.
console.log(Array.isArray(fruits));
There are many more array methods in JavaScript, but these are some good ones to start with.
The ones I use most often are probably push(), pop(), shift(), unshift(), slice(), splice(), and concat().
Top comments (0)