Javascript var, let, const разница

Запомните три пункта, чтобы отличить var, let, const.

  1. Объявление — Можем ли мы повторно объявить его в том же коде?
  2. Область действия блока — Может ли значение быть установлено только в блок? или оно действует как глобальное?
  3. Можно ли переназначить значение? Или можно объявить без значения, а затем присвоить значение?

На примере ниже мы можем хорошо понять все вышеперечисленные моменты.
Примечание: Если вы не знаете, что такое область видимости в Javascript, просто погуглите 🙂

var x=9; //Declared 1st time
var x=10; //Declared 2nd time: Allowed here

let v=9; //Declared 1st time
let v=2; //Declared 2nd time: Not allowed as both in same scope (comment down this line and execute in browser console).

const PI; //Declared 1st time without value assign: Not allowed as const needs value assigned at the time of declaration (comment down this line and execute in browser console).
const PI=3.14; //Declared 2nd time: Allwed as it is proper declaration.

PI=3.14159; //Reassign const value: Not allowed (comment down this line and execute in browser console).


function BlockScope(){

console.log('----------block space start-----------');

var x=2; //Declared 3rd time: Allowed here
console.log(x); //x will be 2 over here

let v=3; // Declared 3rd time: Allowed as scope is changed here.
console.log(v); //v will be 3 over here 

const PI=3.1415; //Declared 3rd time: allowed as it follow Scope Principle.

console.log(PI); //PI will be 3.1415

console.log('----------block space end-----------');
}

BlockScope();

console.log(x); //x will be 2 which do not follow block scope (means var do not follow scope principle).

console.log(v); // v will be 9 here (means let follow scope principle).

console.log(PI); // PI will be 3.14 and not 3.1415 as it follow scope principle.

v=12; //allowed and value will be chagned to 12 when you run(3rd point) 


Вход в полноэкранный режим Выход из полноэкранного режима

Оцените статью
devanswers.ru
Добавить комментарий