Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Let 2/2 | Data Types and Variables
Introduction to JavaScript

book
Let 2/2

let Does Not Allow Redeclaration

Redeclaration means declaring a variable again. As discussed in the previous chapter, we can redeclare the variable again and again with var but we cannot do that with the let keyword.

var number = 5;
var number = 3;
console.log(number);
123
var number = 5; var number = 3; console.log(number);
copy

But a variable declared with let does not allow redeclaration.

let number = 5;
let number = 3;
console.log(number);
123
let number = 5; let number = 3; console.log(number);
copy
Uppgift

Swipe to start coding

A variable named country with two values Pakistan and England has been given declared for you using the let keyword but this code won’t run because let doesn’t allow redeclaration. Your task is to make changes in the below code so that we England as the output. There are two possible ways to do get the desired result.

Lösning

let country = "Pakistan";
country = "England";
console.log(country);
//OR
//var country = "Pakistan";
//var country = "England";
//console.log(country);

Note: Solution-2 is not much preferable.

let Does Not Allow Hoisting

As discussed in the previous chapter, let does not allow hoisting i.e. we cannot use a variable before the declaration. Variables declared with the var keyword can be accessed or used before the declaration, for example.

planet = 'earth';
console.log(planet);
var planet;
123
planet = 'earth'; console.log(planet); var planet;
copy

But let does not allow hoisting.

planet = 'earth';
console.log(planet);
let planet;
123
planet = 'earth'; console.log(planet); let planet;
copy

Summary:

  • let is the newer way to declare variables.

  • let has block scope.

  • let does not allow redeclaration.

  • let does not allow hoisting.

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 3. Kapitel 8
single

single

let country = "Pakistan";
let country = "England";

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

some-alt