Naming Values With const and let

The rebalancing crew’s Python script still runs before every shift, and the crew lead is waiting for the JavaScript version. You’ll port it one piece at a time, and the first piece is the smallest: the lines that give one dock’s numbers a name. This morning, Harbor Square has 14 bikes and 1 free slot.

In Python, naming a value takes nothing more than =. In JavaScript, every name starts with a keyword, and the keyword you pick tells the reader whether the name will ever be reassigned.

Declare Each Name Once

The Python script opens with a comment and three assignments, then prints them:

Language: Python
# Harbor Square, from this morning's dock list
name = "Harbor Square"
bikes = 14
slots = 1
print(name, bikes, slots)

Your port goes in dock-report.js, in a folder named dock-report/ whose package.json holds { "type": "module" }.

In JavaScript, every name starts with a declaration. The "type": "module" setting runs the file in strict mode, where assigning to a name that was never declared stops the file with a ReferenceError. Here’s Harbor Square in JavaScript, each name declared with const:

Language: JavaScript
// Harbor Square, from this morning's dock list
const name = "Harbor Square";
const bikes = 14;
const slots = 1;
console.log(name, bikes, slots);

Run it with node dock-report.js, and it prints what Python did:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.