El Salvador achieved independence from Spain in 1821 and from the Central American Federation in 1839 .