You get 3
in the second case because the second command $(...)
(i.e. command substitution) executes in a subshell.
From the manual:
Command substitution, commands grouped with parentheses, and asynchronous commands are invoked in a subshell environment that is a duplicate of the shell environment, ...