What is difference between script: and before_script: inside a job in gitlab-ci.yml

It's mostly useful for jobs to add or override steps when using include: (templates) and/or extends: and/or globals/default for before_script as you mentioned.

For example, you may create a hidden key job that defines script: intended to be extended by other jobs. Those jobs which extend it can provide a before_script: key without overriding script: or vice versa.

.install_dependencies:
  before_script:
    - pip install --upgrade pip
    - pip install -r requirements.txt

my_test_job:
  extends: .install_dependencies
  script:
    - pytest

So, it's just for composition of jobs. Otherwise, there is no difference. before_script: and script: are simply concatenated together when the job runs.

It's worth mentioning also that after_script: is significantly different than script:/before_script:. after_script runs in a separate shell instance and will run under different circumstances. See the docs for more info.