Creating Objects in JavaScript
In JavaScript, we can create objects to store related information in key-value pairs.
For example, imagine we want to store laptop details such as model, RAM, storage, and screen size.
We can create two separate objects like this:
const lenovo = {
model: "ThinkPad",
ram: 8,
rom: 512,
screen: 15.5
};
const dell = {
model: "Latitude",
ram: 16,
rom: "1TB",
screen: 14.5
};
console.log(lenovo);
console.log(dell);
This works perfectly. But what if we need to create 10 or 20 laptop objects?
Writing the same properties again and again takes more time and makes the code repetitive.
Is there a better way?
Yes! We can use a Constructor Function.
Object Constructor Function
A constructor function is a reusable function used to create multiple objects with the same structure.
Let's create a laptop constructor function.
function Laptop(model, ram, rom, screen) {
this.model = model;
this.ram = ram;
this.rom = rom;
this.screen = screen;
}
const lenovo = new Laptop("ThinkPad", 8, 512, 15.5);
const dell = new Laptop("Latitude", 16, "1TB", 14.5);
console.log(lenovo);
console.log(dell);
Now we can create multiple laptop objects without repeating the same property definitions.
Understanding the code
- function Laptop() – Constructor function.
- model, ram, rom, screen – Parameters.
- this – Refers to the newly created object when called with new.
- new – Creates a new object and calls the constructor function to initialize it.
What does this mean?
The this keyword refers to the current object.
For example:
function Laptop(model, ram) {
this.model = model;
this.ram = ram;
}
const lenovo = new Laptop("ThinkPad", 8);
const dell = new Laptop("Latitude", 16);
console.log(lenovo.model); // ThinkPad
console.log(dell.model); // Latitude
Here, this.model refers to the model property of the object currently being created.
My understanding:
Constructor functions are useful when we need to create multiple objects with similar properties.
Truthy and Falsy Values
This is another interesting concept in JavaScript.
Sometimes, we use values directly inside an if condition without comparing them with true or false.
JavaScript automatically converts those values into Boolean values.
This behaviour is called Truthy and Falsy.
Truthy Values
A truthy value is a value that becomes true when converted into a Boolean.
Examples:
- Non-empty strings ("Hello")
- Non-zero numbers (10, -5)
- Arrays ([], [1, 2])
- Objects ({})
- Functions
Falsy Values
JavaScript has seven falsy values:
- false
- 0
- -0
- 0n
- ""
- null
- undefined
- Nan
Example 1: Truthy Value
let s = "JavaScript";
if (s) {
console.log("Truthy!");
} else {
console.log("Falsy!");
}
Output:
Truthy!
Why? Because "JavaScript" is a non-empty string.
Example 2: Falsy Value
let s = "";
if (s) {
console.log("Truthy!");
} else {
console.log("Falsy!");
}
Output:
Falsy!
Because an empty string is a falsy value.
One interesting point
Even an empty array and an empty object are truthy in JavaScript!
console.log(Boolean([])); // true
console.log(Boolean({})); // true
console.log(Boolean("")); // false
console.log(Boolean(0)); // false
This is something worth remembering when writing conditional statements.
Arrays in JavaScript
An array is used to store multiple values in a single variable.
For example, instead of creating separate variables for every subject mark, we can store all the marks inside one array.
const marks = [70, 89, 77, 32, 46];
console.log(marks);
Output:
[70, 89, 77, 32, 46]
Key Characteristics of JavaScript Arrays
- Elements: An array is a list of values, known as elements.
- Ordered: Array elements are ordered based on their index.
- Zero indexed: The first element is at index 0, the second at index 1, and so on.
- Dynamic size: Arrays can grow or shrink as elements are added or removed.
- Heterogeneous: Arrays can store elements of different data types (numbers, strings, objects and other arrays).
JavaScript Array Methods
JavaScript provides many built-in array methods that make working with arrays easier.
Let's look at some commonly used methods.
1. length
The length property returns the total number of elements in an array.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let size = fruits.length;
console.log(size);
Output:
4
2. toString()
The toString() method converts an array into a comma-separated string.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let myList = fruits.toString();
console.log(myList);
Output:
Banana,Orange,Apple,Mango
It returns a string and does not modify the original array.
3. concat()
The concat() method is used to combine two or more arrays.
For example, let's combine two arrays containing boys' and girls' names.
const myGirls = ["Cecilie", "Lone"];
const myBoys = ["Emil", "Tobias", "Linus"];
const myChildren = myGirls.concat(myBoys);
console.log(myChildren);
Output:
["Cecilie", "Lone", "Emil", "Tobias", "Linus"]
The concat() method creates a new array without changing the original arrays.
JavaScript Array Iterations
JavaScript provides 3 simple statements for looping over each array items:
- for ... of (loops over values)
- for ... in (loops over indexes)
- forEach (myFunction)
const cars=["BMW","Volvo","Mini"];
for(let car of cars){
console.log(car);
}
output:
BMW
Volvo
Mini
Top comments (0)