"Say what, now?" Breaking Down JavaScript Building Blocks for Algorithmically-Challenged Thinkers
Tags: javascript, beginners, codenewbie
Published: 2023-04-07 19:26:21

Reader, if you're anything like me, you probably excel at logical reasoning, but really struggle to translate those concepts into procedural steps. If you're trying to learn to code, but are experiencing challenges turning conceptual _why_'s into their procedural _how_'s, I'm hoping you'll find this breakdown of JavaScript's three main building blocks: `variables`, `functions`, and `scope` to be of use.

---

### JS Variables

A **variable** is simply the named storage location for a piece of data.

<aside>
💡 When naming variables, avoid using [reserved words](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#reserved_words) or [future reserved words](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#future_reserved_words).

</aside>

**Once named, variables then need to be _initialized_, which requires two steps:**

1. Declaring (using `let`, `const`, or `var`)
2. Assigning (this is the data to the right of the =)
    a. These two steps can be completed in a single line of code, but there will be times when it makes more sense to declare the variable without immediately assigning it a value.

When to use `let`, `const`, or `var`:

`var` can lead to scope-related bugs, so it is ***almost* never used**.

`const` is the go-to option as its **variables can neither be redeclared nor reassigned**

> **Note:** values must be assigned immediately when using `const` to declare variables!
> 

`let` should be used **when you know the variable’s value will change** (i.e. a counter)

<aside>
💡 Best practice: always start by declaring variables with `const`! If you later realize that its value will need to change over time, go back and adjust it to `let`.

</aside>

## [Functions in JS](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions)

**A function is essentially a procedure** — you’re telling JS to perform a task by taking an input and returning an output.

A **function declaration** (aka function definition or statement) is made up of the `function` keyword followed by:

- The function *name*
- The function *parameters* (enclosed in parentheses & separated by commas)
      - _Parameters_ are locally-scoped variables that are usable ("scoped") to inside the function. They’re defined inside the function’s declarations `()`.
- The JS statements which *define* the function (enclosed in curly brackets)

```jsx
function funcName(parameter){
	return whatYouWantFunctionToOutput;
	}
```

**Declaring a function** = giving it a name & telling it what to do, it **does not execute it.**

**A function has to be *called* to perform** the actions with the indicated parameter, like such:

```jsx
funcName(parameterArgument);
```

When called, functions must be in scope; however, function declarations can also be hoisted (appearing below the call), like such:

```jsx
funcName(parameterArgument);

function funcName(parameter) {
	return whatYouWantFunctionToOutput;
	}
```

**Function Return Values**

Return values are simply values that a function returns when completing its task. 

The values being returned could be one of the following:

- `string`
- `number`
- expression (such as `1 + 1`)

When a `return` is reached in the code, the `return` will be executed, but if there is any code after that point, that code will **not** be executed.

### [Arrow Functions](https://www.w3schools.com/js/js_arrow_function.asp)

Arrow functions allow users to write shorter function syntax:

```jsx
let myFunction = (a, b) => a * b;
```

For example, this is standard syntax:

```jsx
hello = function() {
	return "Hello World!";
}
```

Whereas this is the same function using the arrow format:

```jsx
hello = () => {
	return "Hello World!";
}
```

Further, if the function has only one statement and the statement returns a value, the brackets *and* the `return` keyword can be removed:

```jsx
hello = () => "Hello World!";
```

If the function has parameters, they’ll be passed inside the parentheses:

```jsx
hello = (val) => "Hello" + val;
```

If there’s only one parameter, the parentheses can be removed entirely:

```jsx
hello = val => "Hello" + val;
```

**Callback Functions**

A **callback** is a **function passed as an argument to another function**, to be “called back” at a later time (as opposed to being executed immediately).

For example:

```jsx
//function
function greet(name, callback) {
	console.log('Hi' + ' ' + name);
	callback();
	}

//callback function
function callMe() {
	console.log('I am a callback function');
	}
//passing function as an argument
greet('Lauren', callMe);

//returned:
>>"Hi Lauren I am a callback function"
```

## [Scope](https://medium.com/@aastha6348/understanding-scopes-and-scope-chain-in-javascript-4d87f7a4b144)

In JS, ***scope* refers to the current context of the code**; wherein, which variables and functions can be accessed. 

> **Note:** where you define a variable or function in JS determines where it can be accessed later on!
> 

For instance, if a variable is defined within a function, it cannot be accessed outside of that function.

There are several types of scope in JS:


![Scope Image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y2fe4pnke77153l06tis.png)

**Global Scope**

**Global scope** means that a **variable or function is available** (and therefore accessible) **anywhere in the code or program.**

```jsx
//Global Scoped Variable
const global_variable = "Flatiron School"

//First function
function first_func() {
	return global_variable;
	}
//Second function
function second_func() {
	return first_func();
	}

console.log(second_func());
//output = Flatiron School
```

**Local Scope**

**Local scope** means that a **variable or function is only available within its code block**. Local scope is created with curly brackets `{}`.

**Scope Chain**

**Scope chain** is the **process by which JS determines which variables & objects are referenceable** based off their location in the code.

**Lexical Scope**

**Lexical scope** means that a **variable’s scope is determined by its position in the code** (namely, they must be located within the same scope as their parent variables).

---

As someone with a liberal arts background who has recently elected to step into a new realm of education and career-building, I've struggled greatly with internally translating coding vocabulary into layman's terms to better understand JavaScript's language and building principles. If, reader, you've found yourself with the same struggles, I sincerely hope this breakdown has been of positive use.

A quick note about sources: the primary sources utilized for this post came from lectures and curriculum provided by Flatiron School. Any external sources have been linked throughout.