Slices in JavaScript // Unlike arrays, JavaScript arrays are dynamic and can grow or shrink in size.
// They are similar to slices in functionality.
// Create an empty array
let s = [];
console . log ( "uninit:" , s , s === null , s . length === 0 );
// Create an array with initial size
s = new Array ( 3 );
console . log ( "emp:" , s , "len:" , s . length );
// We can set and get just like with arrays
s [ 0 ] = "a" ;
s [ 1 ] = "b" ;
s [ 2 ] = "c" ;
console . log ( "set:" , s );
console . log ( "get:" , s [ 2 ]);
// length returns the length of the array as expected
console . log ( "len:" , s . length );
// In JavaScript, we can use the push method to append elements
s . push ( "d" );
s . push ( "e" , "f" );
console . log ( "apd:" , s );
// To copy an array, we can use the spread operator or slice method
let c = [... s ];
// Alternatively: let c = s.slice();
console . log ( "cpy:" , c );
// JavaScript arrays support slicing with the slice method
let l = s . slice ( 2 , 5 );
console . log ( "sl1:" , l );
// This slices up to (but excluding) index 5
l = s . slice ( 0 , 5 );
console . log ( "sl2:" , l );
// And this slices up from (and including) index 2
l = s . slice ( 2 );
console . log ( "sl3:" , l );
// We can declare and initialize an array in a single line
let t = [ "g" , "h" , "i" ];
console . log ( "dcl:" , t );
// JavaScript doesn't have a built-in slices package, but we can implement
// similar functionality
// Function to check if two arrays are equal
function arraysEqual ( arr1 , arr2 ) {
return arr1 . length === arr2 . length &&
arr1 . every (( value , index ) => value === arr2 [ index ]);
}
let t2 = [ "g" , "h" , "i" ];
if ( arraysEqual ( t , t2 )) {
console . log ( "t == t2" );
}
// JavaScript arrays can be multi-dimensional and jagged
let twoD = [];
for ( let i = 0 ; i < 3 ; i ++ ) {
twoD [ i ] = [];
for ( let j = 0 ; j < i + 1 ; j ++ ) {
twoD [ i ][ j ] = i + j ;
}
}
console . log ( "2d: " , twoD );
Note that while JavaScript arrays are different from Go slices, they provide similar functionality and are often used in a similar way. JavaScript arrays are dynamic by nature, so they can grow and shrink without explicit resizing.
To run this JavaScript code, you can save it in a file (e.g., arrays.js
) and run it using Node.js:
$ node arrays.js
uninit: [] false true
emp: [ <3 empty items> ] len: 3
set: [ 'a' , 'b' , 'c' ]
get: c
len: 3
apd: [ 'a' , 'b' , 'c' , 'd' , 'e' , 'f' ]
cpy: [ 'a' , 'b' , 'c' , 'd' , 'e' , 'f' ]
sl1: [ 'c' , 'd' , 'e' ]
sl2: [ 'a' , 'b' , 'c' , 'd' , 'e' ]
sl3: [ 'c' , 'd' , 'e' , 'f' ]
dcl: [ 'g' , 'h' , 'i' ]
t == t2
2d: [ [ 0 ] , [ 1, 2 ] , [ 2, 3, 4 ] ]
JavaScript arrays are versatile and can be used to implement various data structures. They come with many built-in methods for manipulation and iteration, making them a powerful tool in JavaScript programming.
Now that we’ve seen arrays in JavaScript, we’ll look at another key built-in data structure: objects, which are similar to maps in other languages.