-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path09-shiftMethod.js
More file actions
79 lines (54 loc) · 2.31 KB
/
09-shiftMethod.js
File metadata and controls
79 lines (54 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*JavaScript Array shift() Method
The shift() method in JavaScript is used to remove the first element of an array,
reducing the array’s length by one. This method is particularly useful for scenarios
where elements need to be processed in the order they were added, such as in queue-like structures.
Syntax:
arr.shift();
Parameters:
This method does not accept any parameter.
Return Value:
This function returns the removed first element of the array.
If the array is empty then this function returns undefined.
Note: This function can also be used with other javascript objects that behave like the array.
Key Points
The shift() method modifies the original array.
It can be used with other JavaScript objects that behave like arrays (e.g., array-like objects).
Indices of the remaining elements are adjusted, decrementing by one to fill the gap left by the
removed element.
Examples of Array shift() Method*/
/*Example 1: Removing the First Element from the Array
The function func() removes the first element from array
using the shift() method. The removed element is stored
in the variable, value, which is then logged to the console
along with the modified array.*/
// Original array
let array = ["GFG", "Geeks", "for", "Geeks"];
// Checking for condition in array
let value = array.shift();
console.log(value);
console.log(array);
// Output
// GFG
// [ 'Geeks', 'for', 'Geeks' ]
// Example 2: Removing First Element from Empty Array
// The function func() attempts to remove the first element from an empty array array using the shift() method. Since the array is empty, shift() returns undefined, which is logged to the console along with the unchanged array.
// Original array
let arr = [];
// Checking for condition in array
let val = arr.shift();
console.log(val);
console.log(arr);
// Output
// undefined
// []
// Example 3: Removing the First Element from the Nested Array
// The function func() removes the first element from the nested array using the shift() method. The removed element is stored in the variable value, which is then logged to the console along with the modified array.
// Original array
let arr1 = [1,[2,3,4],5,6];
// shift method on nested array
let val1 = arr1[1].shift();
console.log(val1);
console.log("Array after operation: "+ arr1);
// Output
// 2
// Array after operation: 1,3,4,5,6