Does it matter if you set a const function as let function?


#1

https://www.codecademy.com/courses/learn-javascript-functions/lessons/functions/exercises/parameters-ii?action=lesson_resume&course_redirect=introduction-to-javascript

In this exercise, they add parameters so you can pass arguments through the function. They tell you to make the function const, even though you give it can different arguments every time you run the code. I thought that const variables cant be changed so why would the function be classified const. Also, can you make a let function?

const takeOrder = (topping) => {
	console.log(`Order: pizza topped with ${topping}.`);
}

takeOrder('jalapenos');

Does it matter if I change const to let? When I try i get a red bar on the bottom of the code editor that says [Function expected.


#2

It only matters if we wish to protect the function. A function defined by an expression can be replaced with another function expression, but as a const, it cannot.

const foo = x => x + x;

console.log(foo("21"));    // =>  2121
console.log(foo(21));      // =>  42

// add after first run
foo = x => x + "bar";
console.log(foo('foo'));
SyntaxError: Assignment to constant variable: foo at 7:0

Using let on the variable would permit assignment of arbitrary types or values during the session.

let foo = x => x + x;

console.log(foo("21"));
console.log(foo(21));

foo = x => x + "bar";
console.log(foo('foo'));
2121
42
foobar

#3

Thank you, I wasn’t aware that you could change the function expression in the code later.


#4

It is not something that we see a lot of, but we can make it interesting if the scenario arises.

const foobar = x => typeof x === 'string' ? x => x + "bar" : x => x + x;

console.log(foobar('')('foo'));
console.log(foobar(0)(21));
 foobar
 42
=> undefined

#5

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