Search code examples
javascriptif-statementsplice

What am I doing wrong with .splice()


I'm just trying to get comfortable with .slice(), and .splice(). Why doesn't this code work? According to w3Schools .splice() takes 3 arguments, (index at which to begin adding/removing elements, # of elements to be removed, and what to add). Why does this function not work? P.S. Ignore they y, its just there as part of my experimenting.

let x = "Hello I like milk";
let y = ''

if(x[0] !== '(') {
 x = x.split(' ').splice(0, 0, '(');


}






console.log(x)

Solution

  • splice() returns a removed items. Well the original array is changed, but you replaced it with the return value of splice(), resulting no elements. If you mean to add element at the beginning of the array, it should be like this

    let x = "Hello I like milk";
    let y = ''
    
    if(x[0] !== '(') {
        x = x.split(' ');
        x.splice(0, 0, '(');
    }
    
    console.log(x)