Kursinnhold
Introduction to JavaScript
Introduction to JavaScript
Adding Values to an Array
After defining an array, we can further add some elements to it using the push
method.
A methods is a function that belongs to an object and is called using that object. The main difference is that a function is independent, while a method is tied to an object and is called using object.methodName()
. For example, in this case the object is the array and the method is push
.
The general syntax of the push
method is:
python
Here arrayName
is the name of the array to which we want to add the element, and value1
, value2
and so on are the elements we want to add to that array.
Pushing an element to an array adds it to the end of the array:
let fruits = ["Apple", "Banana"]; console.log(fruits); // Output: ["Apple", "Banana"] fruits.push("Cherry"); console.log(fruits); // Output: ["Apple", "Banana", "Cherry"]
Notice how "Cherry"
was added to the end of the fruits array using the push
method.
If we have multiple values to push, they are pushed in the same order they were mentioned:
let fruits = ["Apple", "Banana"]; console.log(fruits); // Output: ["Apple", "Banana"] fruits.push("Cherry", "Mango"); console.log(fruits); // Output: ["Apple", "Banana", "Cherry", "Mango"]
1. What does the push
method do in JavaScript?
2. Which of the following is the correct syntax for using the push
method?
3. What will be the output of the following code?
Takk for tilbakemeldingene dine!