Vkrm Vkrm - 20 days ago 5
Javascript Question

React-Native Navigation Experimental(NavigationStateUtils), purpose of using a slice?

React-Native Navigation Experimental on NavigationStateUtils.js,

What is the purpose of Using a Slice over here, as it returns same exact array of routes even though slice() is not used.

enter image description here

https://github.com/facebook/react-native/blob/9ee815f6b52e0c2417c04e5a05e1e31df26daed2/Libraries/NavigationExperimental/NavigationStateUtils.js#L66

Or it is Just there to be consistent with pop.

enter image description here

lt1 lt1
Answer

The purpose is probably to create a copy of the state.routes array before modifying it, so as not to mutate the original array referenced by state.routes. Keeping your data structures immutable (by making a copy that you modify, rather than modifying the original) can help to avoid unexpected bugs when an array/object/etc. is modified by some other part of the code. It's a commonly used principle in Functional programming, a paradigm which React generally adheres to.