let , const and arrow functions in javascript
Tags: javascript, webdev, beginners, programming
Published: 2022-01-27 02:59:42

In this blog I will try to explain the `let` and `const` keyword in javascript and also talk about `arrow functions`. 

These are new features added to the ES6 JavaScript ( ECMAScript 2015 was the second major revision to JavaScript. ECMAScript 2015 is also known as ES6 and ECMAScript 6.)

Before we understand `let` and `const` we must understand what scope means in javascript.

Scope determines the accessibility or visibility of variables.

JavaScript has 3 types of scope:

`Block scope`: 

- Before ES6 (2015), JavaScript had only **Global Scope** and **Function Scope**
- ES6 introduced two important new JavaScript keywords: `let` and `const.`
- These two keywords provide Block Scope in JavaScript.
- Variables declared inside a `{ }` block cannot be accessed from outside the block:
- Variables declared with the var keyword can NOT have block scope.
- Variables declared inside a `{ }` block can be accessed from outside the block.

```jsx

{
  let y = 2;
  var x = 2;
}
// y can NOT be used here
// x CAN be used here
```

`Function scope`

- JavaScript has function scope: Each function creates a **new** scope.
- Variables defined inside a function are not accessible (visible) 
from outside the function.
- Variables declared with `var`, `let` and `const` are quite similar when 
declared inside a function.

They all have Function Scope:

```jsx

const myFunction = () => {
  var carName = "something";   // Function Scope
}
const myFunction = () => {
  let carName = "is";   // Function Scope
}
const myFunction = () => {
  const carName = "up";   // Function Scope
}
```

`Global scope`

- Variables declared Globally (outside any function) have **Global Scope**.
- Global variables can be accessed from anywhere in a JavaScript program.
- Variables declared with `var`, `let` and `const` are quite similar when 
declared outside a block.

They all have Global Scope:

```jsx

var x = 2;       // Global scope
let x = 2;       // Global scope
const x = 2;       // Global scope
```

Now that we know what scope means in javascript lets understand what the let keyword does

<aside>
💡 The Lifetime of JavaScript Variables:
The lifetime of a JavaScript variable starts when it is declared. Function (local) variables are deleted when the function is completed. In a web browser, global variables are deleted when you close the browser window (or tab).

</aside>

<aside>
💡 Function Arguments :
Function arguments (parameters) work as local variables inside functions

</aside>

---

### let keyword

The `let` keyword allows you to declare a variable with block scope.

```jsx
var a = 10;
// Here a is 10
{
  let a = 15;
  // Here a is 15
}
// Here a is 10
```

- Variables defined with `let` cannot be Redeclared.
- Variables defined with `let` have Block Scope.

```jsx
let x = "something";
let x = 0;

// SyntaxError: 'x' has already been declared
```

---

### const keyword

- The `const` keyword allows you to declare a constant (a JavaScript variable with a constant value).
- Constants are similar to let variables, except that the value cannot be changed.

```jsx
var x = 40;
// Here x is 40
{
  const x = 22;
  // Here x is 22
}
// Here x is 40
```

- Variables defined with `const` cannot be Redeclared.
- Variables defined with `const` cannot be Reassigned.
- Variables defined with `const` have Block Scope.

When should we use JavaScript const?

As a general rule, always declare a variable with `const` unless you know that the value will change.

Use `const` when you declare:

- A new Array
- A new Object
- A new Function
- A new RegExp

But But But...

The keyword `const` is a little misleading.

It does not define a constant value. It defines a constant reference to a value.

Because of this you can NOT:

- Reassign a constant value
- Reassign a constant array
- Reassign a constant object

But you CAN:

- Change the `elements` of constant array
- Change the `properties` of constant object

```jsx
// You can create a constant array:
const cars = ["KIA", "Volvo", "BMW"];

// You can change an element:
cars[0] = "Toyota";

// You can add an element:
cars.push("Audi");

const cars = ["Kia", "Volvo", "BMW"];

cars = ["Toyota", "Volvo", "Audi"];    // ERROR

---------------------------------------------

// You can create a const object:
const car = {type:"Fiat", model:"500", color:"white"};

// You can change a property:
car.color = "red";

// You can add a property:
car.owner = "Batman";

const car = {type:"Ford", model:"900", color:"white"};

car = {type:"Volvo", model:"E860", color:"black"};    // ERROR
```

<aside>
💡 Do NOT create global variables unless you intend to. Your global variables (or functions) can overwrite window variables (or functions).Any function, including the window object, can overwrite your global variables and functions.

</aside>

---

### arrow functions

Arrow functions allows a short syntax for writing function expressions.

You don't need the `function` keyword, the `return` keyword, and the **curly brackets**.

```jsx
// ES5
var a = function(a, b) {
   return a * b;
}

// ES6
const a = (a, b) => a * b;
```

- Arrow functions do not have their own `this`. They are not well suited for defining **object methods**.
- Arrow functions are not hoisted. They must be defined **before** they are used.
- Using `const` is safer than using `var`, because a function expression is always a constant value.
- You can only omit the `return` keyword and the curly brackets if the function is a single statement. Because of this, it might be a good habit to always keep them:

```jsx
const x = (a, b) => { return a * b };
```

- Arrow Functions Return Value by Default:

```jsx
hello = () => "Hello World!";
// Note: This works only if the function has only one statement.
```

- Arrow Function With Parameters:

```jsx
hello = (val) => "Hello " + val;
// In fact, if you have only one parameter, you can skip the parentheses as well:
hello = val => "Hello " + val;
```

### What About this?

- The handling of `this` is also different in arrow functions 
compared to regular functions.
- In short, with arrow functions there are no binding of `this`.
- In regular functions the this keyword represented the 
object that called the function, which could be the window, 
the document, a button or whatever.
- With arrow functions the `this` keyword always represents the 
object that defined the arrow function.

Let us take a look at two examples to understand the difference.

- Both examples call a method twice, first when the 
page loads, and once again when the user clicks a button.
- The first example uses a regular function, and the 
second example uses an arrow function.
- The result shows that the first example returns 
two different objects (window and button), and the 
second example returns the window object twice, because 
the window object is the "owner" of the function.

```jsx

// Example
// With a regular function this represents the object that calls the function:

// Regular Function:
cons hello = function() {
  document.getElementById("demo").innerHTML += this;
}

// The window object calls the function:
window.addEventListener("load", hello);

// A button object calls the function:
document.getElementById("btn").addEventListener("click", hello);

------------------------------------------------

// Example
// With an arrow function this represents the owner of the function:

// Arrow Function:
const hello = () => {
  document.getElementById("demo").innerHTML += this;
}

// The window object calls the function:
window.addEventListener("load", hello);

// A button object calls the function:
document.getElementById("btn").addEventListener("click", hello);
```

If this blog helped you learned something new please drop a like.