Let Statement in JavaScript

  • Videos
  • January 12, 2022
  • 0

Morten Rand-Hendriksen

Topics: JavaScript, Let statement, TitleColor

Transcript Summary

The let statement is a type of statement in JavaScript. The let statement declares a block-scoped local variable, which means it is only defined within the current block. This allows us to securely avoid difficulties with variable scope. Let’s imagine we have a box whose color is equal to the title, and we don’t want that to happen. This is known as a scope problem. To address this problem, we must use let to define a new variable within the function scope. We will than have the right colors. The reason for this is that we are now working within the function’s local scope, and within this function, we can define all new variables using let, and they will only live within that function. This will cause it to overlook everything else that is going on around it. This demonstrates the significance of local scope and how powerful it may be. While working in local scope, we must approach the function as a separate code with its own variables, allowing it to become powerful. Let’s imagine we try to call a locally scoped “let” from outside its local scope for some reason. To accomplish this, we must update the variable’s name here. This variable will be called titleColor, and the titleColor value will be console logged from within its scope and should work then. 

Assume we want to use a locally scoped variable outside of its scope. Two things will happen. The first thing that will happen is that the color of the box will change. The reason for this is that it was the default color provided before JavaScript intervened. Second, it will report errors in the console, such as “Uncaught Reference Error: titleColor is not declared at script.js line (number).” In this situation, it will correspond to the line that we just inserted. It also implies that the titleColor variable is unknown. This is due to the title color being block-scoped to the heading color function and not existing elsewhere. Because of the problem, JavaScript stops rendering at this moment, resulting in a change in the color of the box. This is a problem, but it is the reason for “let” and local scope. We can use a block-scope variable to see whether we are using the variable in a place where we shouldn’t be since JavaScript crashes and throws an exception. Furthermore, it allows us complete control over when a variable exists and what we can do with it. If we wish to use a variable that can be changeable or mutable, we should use “let” because it will apply everywhere except where you re-declare it in a global scope. 

Supply Chain Effects Of Ecommerce

Math Operators in JavaScript