Why is the function defined as constant


#1

Can some one please explain why the function pressPowerButton is defined as constant?



let calculatorIsOn = false;

const pressPowerButton = () => {
  if (calculatorIsOn) {
    console.log('Calculator turning off.');
    calculatorIsOn = false;
  } else {
    console.log('Calculator turning on.');
    calculatorIsOn = true;
  }
};

pressPowerButton();
// Output: Calculator turning on.

pressPowerButton();
// Output: Calculator turning off. 



#2

well, es6 introduced block scopes (const and let) which are better practice then var (which looks like it has a block scope, but hasn’t)

so then the choice between let and const, you should pick const given the function isn’t going to get re-assigned.


#3

@netwhiz74250 generally const is used in most cases, and let is used declare the variables with values that can be re-assigned, in the example calculatorIsOn can be reassigned to hold a value like true.


#4

@stetim94 and @tommygebru
So can I assume all the functions can be declared as const ?


#5

in most cases, yes, but in programming very few things are absolute

If you need to re-assign the variable that holds the function, you need let

also, if you need function scope you need var, if block scope (let, const) doesn’t suit the design of your program


#6

@stetim94
thanks for the clarification!


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.