Function, Objects and Array In JS.
Source: Dev.to
Functions
A function is a block of code that performs a specific task and can be reused. There are three ways to define a function in JavaScript:
- Function Declaration
- Function Expression
- Arrow Function (ES6) – short syntax, commonly used in modern JS.
Examples
// Function Declaration
function greet(name) {
return "Hello " + name;
}
console.log(greet("Ajmal"));
// Function Expression
const add = function (a, b) {
return a + b;
};
console.log(add(5, 3));
// Arrow Function
const multiply = (a, b) => a * b;
console.log(multiply(4, 2));
Objects
Objects store data in key‑value pairs and combine state with behavior.
const person = {
firstName: "John", // Property
lastName: "Doe", // Property
age: 50, // Property
fullName: function() { // Method
return this.firstName + " " + this.lastName;
}
};
console.log(person.fullName()); // "John Doe"
Arrays
An array in JavaScript is used to store multiple values in a single variable.
Creating an Array
let fruits = ["Apple", "Banana", "Orange"];
Accessing Elements
console.log(fruits[0]); // Apple
console.log(fruits[2]); // Orange
Length
console.log(fruits.length); // 3
Modifying Elements
fruits[1] = "Mango";
console.log(fruits); // ["Apple", "Mango", "Orange"]
Common Array Methods
-
push()– add at endfruits.push("Grapes"); -
pop()– remove from endfruits.pop(); -
unshift()– add at startfruits.unshift("Pineapple"); -
shift()– remove from startfruits.shift();