DEV Community

Mohamed Ajmal
Mohamed Ajmal

Posted on

Function, Objects and Array In JS.

FUNCTION :

A function is a block of code that performs a specific task and can be reused. There are three ways!

1.Function Declaration,
2.Function Expression,
3.Arrow Function (ES6) (Short syntax, Commonly used in modern JS).

Examples:

1.
function greet(name) {
return "Hello " + name;
}

console.log(greet("Ajmal"));

  1. const add = function (a, b) { return a + b; };

console.log(add(5, 3));

3.const multiply = (a, b) => a * b;

console.log(multiply(4, 2));

OBJECTS: An object stores data in key-value pairs. It's a combination of state and behavior.

ex:
const person = {
firstName: "John", // Property
lastName: "Doe", // Property
age: 50, // Property
fullName: function() { // Method
return this.firstName + " " + this.lastName;
}
};

ARRAY - An Array in JavaScript is used to store multiple values in a single variable.

Creating an Array:

let fruits = ["Apple", "Banana", "Orange"];

Access Array Elements:

console.log(fruits[0]); // Apple
console.log(fruits[2]); // Orange

Array Length:

console.log(fruits.length); // 3

Modify Array Elements:

fruits[1] = "Mango";
console.log(fruits);

Common Array Methods:

πŸ”Ή push() – add at end - fruits.push("Grapes");

πŸ”Ή pop() – remove from end- fruits.pop();

πŸ”Ή unshift() – add at start- fruits.unshift("Pineapple");

πŸ”Ή shift() – remove from start- fruits.shift();

Top comments (0)