Functions and Variable Scope

CS133JS Beginning Programming: JavaScript

Topics by Week 
1. Intro to JavaScript programming6. Arrays
2. Functions, Variable scope, Operators and Expressions7. Functions again
3. Conditional Statements8. Objects
4. Loops9. DOM
5. Midterm10. Final

 

Table of Contents


Introduction

Q and A

Anouncements

 


Review

 


Variable Scope

Scope means the part of a program in which a variable is recognized by JavaScript.

Example

  1. If you haven't already, put the function definition above into the console. Try using the variable t outside of the function. Is it valid there?

    Note that in the console it says the variable is "not defined", which is different from "undefined". Wow, don't you love this terminology?

    • Not defined means that JavaScript doesn't know about the variable in that scope.

    • Undefined means that no value has been assigned to the variable, but it is a valid variable in that scope.

  2. Now try moving the definition of t outside the function. Is the variable t valid both inside and outside the function now?

Local and Global Variables

Exercise

 

Function Parameters and Scope

Bad Things

Undeclared Variables

Variables used without declaring them become global variables. But this is a bad way to do things because it is not obvious that this is a global variable. This can lead to making mistakes in your code.

Strict mode (a good thing)

You can set JavaScript to prevent you from using undeclared (not defined) variables by enabling strict mode with the statement, "use strict". Here's an example:

Note: in the browser console, you need to enter "use strict"; and the code that follows it without hitting enter. Use shift-enter at the end of each line.

Hoisting

Hoisting is a feature (quirk?) of JavaScript that lets you use a variable before you declare it with var. This is true whether your code is inside or outside a function. When you declare the variable anywhere in a given scope, it will be as if you had declared it at the top of the scope. Try this example:

Declaring variables with let (another good thing)

You can use the keyword let to declare variables instead of var. This will prevent variable hoisting as well as do some other good thing we will discuss later. Try this example:

Declaring variables with const (yet another good thing)

Variables declared with const cannot have a new value assigned to them and they have block scope (like variables declared with let).

Here's an example:

Literal vs. named constants

There are actually two kinds of constants:

Why use constants?

Reference

W3Schools

JavaScript Scope

JavaScript Hoisting

JavaScript Strict Mode

Free Code Camp

Var, Let, and Const – What's the Difference?

 


Creative Commons License Beginning JavaScript Lecture Notes by Brian Bird, written in 2018, revised in , are licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.