Nano ASP.NET SaaS Boilerplate
Admin credentials (all tenants): admin@email.com / Password123!
Sample data resets every hour
Nano ASP.NET SaaS Boilerplate
General
Front-End Development
Front-End Development

Using Let & Const

Understanding the basics of programming like variables, functions, objects, arrays and loops, is perhaps the most important step in the journey. Everything on the web is constructed using these relatively simple building blocks. If you’ve completed the fundamentals section on coding basics, then you are well on your way!

After you complete this course, check out the Nano ASP.NET Boilerplate. Its an adaptable project template with several front-end projects; a great learning resource and time accelerator for intermediate and advanced developers.

In the last section we made a user interface structured with HTML and CSS. Now all we need to do is add JavaScript to make it work. Before we continue working on the web application, there is one important syntactical distinction to learn about JavaScript before we go any further.

In the JavaScript we saw in the coding basics lesson, we used the keyword var to declare variables.

This was the original variable declaration keyword used in JavaScript and it’s easier to understand for beginners. There is nothing wrong with using var and function but modern JavaScript (ES6 and beyond – around 2015) introduced let and const which offer several advantages.

The main difference with let and const is how they handle reassignment rules. The keyword const is the same as var, except that it will not allow you to reassign a value. It is the most restrictive. Also, it’s value must be assigned from the start.

const myVariable = "abc123";
myVariable = "xyz789";  // Error: TypeError: Assignment to constant variable

const anotherVariable;// Error: SyntaxError: Missing initializer in const declaration

An error will be thrown in the above example because we tried to reassign myVariable. Another error will be thrown because a value wasn’t assigned to anotherVariable at initialization.

The keyword let on the other hand, will allow you to reassign a value and doesn’t need a value when it’s declared. It is the least restrictive.

let score = 10;
score = 20;      // Valid reassignment

let anotherScore;  // Valie

No errors will be thrown in the examples above.

  • Use const for values that should never change (configuration, fixed values)
  • Use let when a variable needs to be reassigned (counters, accumulating values)
  • Avoid var in modern code due to its looser rules that can lead to unexpected bugs

By choosing the right declaration keyword, you make your code’s intent clearer and prevent accidental changes to your variables.

One important note about objects is that, while const prevents reassigning the variable itself, it doesn’t make object properties immutable:

const user = { name: "Alice", age: 29 };
user.name = "Bob";     // This works! We're modifying a property, not reassigning 'user'

const user = { name: "John", age: 43 }; // This doesnt work

Same with arrays

const fruits = ["apple", "grapefruit", "orange", "grape", "kiwi"];
fruits.push("watermelon"); // This works! We're adding an item, not reassigning 'fruits'

const fruits = ["banana", "strawberry", "lime"]; // This doesnt work

Modern JavaScript also introduced a more consistent way to define functions using arrow functions assigned to const variables.

// Old way
function calculateArea(width, height) {
  return width * height;
}

// New way
const calculateArea = (width, height) => {
  return width * height;
}

This is called an arrow function and it provides several advantages over the original function declaration format. It offers better consistency, prevention of redefinition, and cleaner scope. As a beginner, its not important to understand deeply all the reasons why this is better, its only important to recognize this syntax when you see it.

When we declare a function using the function keyword, JavaScript creates a variable to store the function in memory. This is why we can use const in the same way. It may be confusing why we use a const instead of let to store a function. If you think about it, the function structure itself doesn’t actually change. Yes the input and output could be different every time but the function itself is a fixed structure, and therefore we use const.

Using let and const instead of var and function is better coding practice when working with JavaScript. You’ll find many examples on the internet using these so its important to recognize the syntax even if you feel more comfortable using var and function as a beginner.

These are not the only differences when using let and const but we’ve covered the new reassignment rules which are the most noticeable.

Lets do an example with all of the concepts we’ve learned so far:

// Using const for the array that won't change
const fruits = ["apple", "grapefruit", "orange", "grape", "kiwi"];

// Function to categorize fruits by length
const categorizeFruits = () => {
  // Using const for values that won't change
  const shortCategory = "short name";
  const mediumCategory = "medium name";
  const longCategory = "long name";
  
  // Using let for counters that will change
  let shortCount = 0;
  let mediumCount = 0;
  let longCount = 0;
  
  // remove the third item
  fruits.splice(2, 1); 
  
  // add a new item
  fruits.push("watermelon"); 
  
  // Using forEach with if-else if structure
  fruits.forEach(fruit => {
    if (fruit.length <= 4) {
      console.log(`${fruit} is a ${shortCategory} fruit`);
      shortCount++;
    } else if (fruit.length <= 6) {
      console.log(`${fruit} is a ${mediumCategory} fruit`);
      mediumCount++;
    } else {
      console.log(`${fruit} is a ${longCategory} fruit`);
      longCount++;
    }
  });
  
  // Output the final counts
  console.log(``);
  console.log(`Categorization complete:`);
  console.log(`${shortCount} fruits with short names`);
  console.log(`${mediumCount} fruits with medium names`);
  console.log(`${longCount} fruits with long names`);
};

// Call the function
categorizeFruits();

Starting from the top, we declare a new array and initialize it with string values using const. Then we create an arrow function. This function takes no parameters.

We declare category names using const with values that will not change. We use let to create counter variables whose values will change.

Using the splice method, we remove the third item from the fruits array, and add a new item to the end with push.

We loop through each item in the array with the forEach method, checking the length of the string in the conditional if statement. At each iteration, we output a statement to the console and increment the counters by one.

Strings encapsulated by backticks are called template literals, and we can use them to substitute values in placeholders areas designated with the dollar sign and braces ${}.

After the forEach loop, we output the final count of each category. The last line of code actually calls the categorizeFruits function.

While its still okay to use var and function, using let and const is better and its what you will see in most examples across the web today. So even if you don’t use them, at least you know what they mean. In the next section we will continue to build the front-end, adding functionality with JavaScript.