The functions and underlying mechanisms of rapid eye movement (REM) sleep remain unclear. Here we show that REM sleep prunes newly formed postsynaptic dendritic spines of layer 5 pyramidal neurons in the mouse motor cortex during development and motor learning. This REM sleep-dependent elimination of new spines facilitates subsequent spine formation during development and when a new motor task is learned, indicating a role for REM sleep in pruning to balance the number of new spines formed over time. Moreover, REM sleep also strengthens and maintains newly formed spines, which are critical for neuronal circuit development and behavioral improvement after learning. We further show that dendritic calcium spikes arising during REM sleep are important for pruning and strengthening new spines. Together, these findings indicate that REM sleep has multifaceted functions in brain development, learning and memory consolidation by selectively eliminating and maintaining newly formed synapses via dendritic calcium spike-dependent mechanisms.