user11121466
user11121466

Reputation:

Why constant declaration in function declaration doesn't throw an error?

const select = document.querySelector('select');
const para = document.querySelector('p');

select.addEventListener('change', setWeather);

function setWeather() {
  const choice = select.value;

  if (choice === 'sunny') {
    para.textContent = 'It is nice and sunny outside today. Wear shorts! Go to the beach, or the park, and get an ice cream.';
  } else if (choice === 'rainy') {
    para.textContent = 'Rain is falling outside; take a rain coat and an umbrella, and don\'t stay out for too long.';
  } else if (choice === 'snowing') {
    para.textContent = 'The snow is coming down — it is freezing! Best to stay in with a cup of hot chocolate, or go build a snowman.';
  } else if (choice === 'overcast') {
    para.textContent = 'It isn\'t raining, but the sky is grey and gloomy; it could turn any minute, so take a rain coat just in case.';
  } else {
    para.textContent = '';
  }
}

there's also link from MDN website https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/conditionals

Upvotes: 0

Views: 863

Answers (2)

Sarvesh Mahajan
Sarvesh Mahajan

Reputation: 924

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered (for more details, visit: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const).

Please find below example, just like "const select" , here I have declared a const variable named "car" of type object, and I am able to alter property "model" of "car" object:

const car = {type:"Fiat", model:"500", color:"white"};
  car.model= "EX60";
  console.log(car);

Upvotes: 1

pavan kumar
pavan kumar

Reputation: 823

See the scope of const variable, its life only exists when the function runs, and ends when function completes, hence when the function is called again it is a new variable which is getting assigned the value. You have to learn about scope of variables.

Upvotes: 0

Related Questions