# Hoisting and Scope

[**Here is a good article**](https://scotch.io/tutorials/understanding-hoisting-in-javascript) filled with awesome Hoisting and variable declaration goodness. Below is an overview.

### Hoisting

{% hint style="warning" %}
**What happens if we call a function before it is defined?**
{% endhint %}

{% embed url="<https://tech.io/snippet/xWW8GGG>" %}

Interpreted languages like Javascript work with functions differently than compiled languages like C++. The interpreter looks through the entire code file and decides the 'proper' order of certain code blocks. For example, it prioritizes function declarations over runnable code.

### **Scope**

Variables and functions are declared within other blocks of code (a loop, for example).

{% hint style="warning" %}
**Can I use a variable anywhere I want?**
{% endhint %}

**Imagine if we never released the memory used by a variable.** When a variable is created, memory is allocated for that data. When the block of code where that variable exists has ended, the memory is released (no longer needed). This helps with the efficiency of the program.&#x20;

{% embed url="<https://tech.io/snippet/6rHENEQ>" %}

The other thing to note is the use of the term `let` in the example above. In Javascript, there are three ways to create variables (which is quite dangerous). Many people will have their own opinions but it is safest to always declare your variables with `let` instead of `var` and *certainly* never leave out the declaration.

### Let vs Var vs Nothing

{% hint style="warning" %}
**Why do I need to declare my variables, anyway? Javascript lets me write `a = 4` and it still works.**
{% endhint %}

<< More to come >>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://cs.brash.ca/unit-4/user-defined-functions/notes.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
