Javascript let Keyword

JS Code Snippets let Keyword
Share:

About

In this code snippet, we’ll learn about the let keyword in Javascript.

In Javascript variables declared with the var keyword can do some pretty weird stuff with like being used before being declared, declaring the same variable multiple times and no variable scope. Coming from a language like C# these “features” seem absolutely awful to me. Luckily the let keyword was added in ES6. If a variable is declared with let it behaves pretty much like you would expect a variable to behave in any other programming language. More specifically the variable has to be declared before being used, it’s scoped and can be declared only once per scope.

Let’s see the example below.

Code:

//console.log(number); //This won't work with let variables.

let number = 5;

MyFunction();

function MyFunction(){
	let number = 10; //This will just override the original value of the variable while within this functions scope.
  console.log(number);
	let text = "Hello."
}

console.log(number);

//console.log(text); //This won't work with let variables.

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger