Some genes are on (sometimes talk about a gene being “expressed’ i.e. its protein product is being made) all the time in all cells. These are often called housekeeping genes as they keep the cell going and functioning well. However, other genes are expressed in some cells and not others and this is what makes each cell type unique. Sometimes genes can be switched on in a specific cell in response to environmental stimulus e.g. drug detoxification genes are expressed when we take medicine to clear it out of our system.
The switching on and off is controlled by special proteins in the cell called transcription factors and transcription co-regulators.
Jennifer’s given a good answer, but I’ll just add a bit more.
From the moment of fertilisation, there is already epigenetics in place on our genomes. Epigenetics is the way genes are slightly modified to say that they are more open or more closed, which affects how easy it is to turn a gene on (if closed, the transcription factors Jennifer mentioned are less likely to get in to a gene to turn it on). Another way to think about epigenetics across our bodies is like highlighting on the script of a play. All of our cells have the entire script, the genome, but each has highlighting, or epigenetic regulation, to point out their lines. This allows our cells to have very different functions and means that individual genes are more likely to be switched on in some cells than others. I guess there is a default for each cell that is set up before birth, but there are lots of ways that this epigenetic highlighting can be altered to allow genes to be more open or more closed as well as control of how many transcription factors there are to switch a gene on or off.