JavaScript Arrays
An array is a data structure that can store multiple values of the same or different data types. In JavaScript, arrays are zero-indexed, meaning the first element has an index of 0. To access an element in an array, you can use its index. For example, the following code will print the first element of the array fruits
:
const fruits = ["apple", "banana", "orange"];
console.log(fruits[0]);
// "apple"
JavaScript arrays have a number of built-in methods that you can use to manipulate them. Some of the most common ways include:
push(): Adds an element to the end of the array.
pop(): Removes the last element from the array.
shift(): Removes the first element from the array.
unshift(): Adds an element to the beginning of the array.
slice(): Creates a new array that contains a slice of the original array.
indexOf(): Returns the index of the first occurrence of an element in the array.
forEach(): Executes a function for each element in the array.
JavaScript Functions
A function is a block of code that is executed when it is called. Functions can be used to encapsulate code and make it reusable. To define a function in JavaScript, you use the function
keyword. For example, the following code defines a function greet()
that takes a name as an argument and returns a string:
function greet(name) {
return `Hello, ${name}!`;
}
To call a function, you use its name followed by parentheses. For example, the following code calls the greet()
function and passes the string "John" as an argument:
const greeting = greet("John");
console.log(greeting); // "Hello, John!"
JavaScript also supports anonymous functions, which are functions that do not have a name. Anonymous functions are often used as callbacks or event handlers.
JavaScript Objects
An object is a data structure that can store data in key-value pairs. The key is a unique identifier for the data, and the value is the data itself. In JavaScript, objects are created using the {}
curly braces. For example, the following code creates an object called person
that has three properties: name
, age
, and profession
:
const person = {
name: "John",
age: 30,
profession: "Web Developer",
};
To access a property in an object, you can use the dot notation or the square brackets notation. The dot notation uses the object's name followed by a period and the property name. For example, the following code uses the dot notation to access the name
property of the person
object:
const name = person.name;
console.log(name); // "Alice"
The square brackets notation uses the object's name followed by square brackets and the property name. For example, the following code uses the square brackets notation to access the name
property of the person
object:
const name = person["name"];
console.log(name); // "Alice"
I hope this explanation is long enough and simple enough for you.