Let in for loops

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 191:- Let in for loops

In ES6, the let keyword was introduced, which has block scope. This means that variables declared with let are only accessible within the block they are declared in. One of the main advantages of let over var is that it can be used in for loops to create block-scoped loop variables.

Consider the following example:

cssCopy code

for (let i = 0; i < 5; i++) {  console.log(i); } console.log(i); // throws an error because i is not defined

In this example, the let keyword is used to declare the loop variable i. Because let has block scope, i is only accessible within the for loop block. Therefore, the console.log(i) statement outside of the loop block will throw an error.

On the other hand, if var had been used instead of let, the loop variable i would have function scope, which means that it would be accessible outside of the for loop block:

cssCopy code

for (var i = 0; i < 5; i++) {  console.log(i); } console.log(i); // outputs 5

In this example, the loop variable i is declared using var, so it has function scope. Therefore, the console.log(i) statement outside of the loop block will output the value of i, which is 5.

21. Closures

2 Comments

@niteshguptav63
niteshguptav63 Nov 17, 2024 at 1:39 PM

I am not able to access videos from second class and further. I have already completed first class

@niteshguptav63
niteshguptav63 Nov 16, 2024 at 10:56 AM

When will I get my course?

@admin79
admin79 Nov 17, 2024 at 1:29 PM

Now, Your query was resolved.

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support