Issue with const

i’ve found something strange and I look for explanations.
In my meteor project, I have a file named collections.js which contains:

const Interventions = new Mongo.Collection(‘interventions’);

(I want to use const to take the habit working with es6)

In my client/interventions.js, I want to get all interventions then I’ve wrote:

interventions: function () {
return Interventions.find({});

My interventions will never be pulled because of the const keyword ? If I remove it, I can get my data.
Can you explain me why please ?

By using the const keyword in your collections.js file you are restricting access to Interventions to within that file (this would be the same thing if you used var or let). By removing const you are then making Interventions a global variable, which means it can then be found in your interventions.js file.

1 Like

thanks for the answer.
I thought that const adds a restricted access on value update, not on access value’s.

const isn’t preventing access to the value directly; this is a javascript scoping issue. By using const you’re making Interventions a local variable to the collections.js file scope. That means it can’t be accessed outside of that file unless you make it a global (or use some other method to make it available).

const and let are even more restrictive than that - they provide block scoping - something Javascript has been lacking:

if (a === 1) {
  const b = 2; // this is a different b ...
} else {
  const b = 3; // ... to this one
// and b isn't even defined here!
console.log(b); // undefined

@gorjuce in Meteor 1.2 and below, JavaScript scope is used to make variables accessible in other files in your app. This unfortunately means you can’t use const to declare those variables. So, for example:

// Accessible in other files
MyVariable = 5;

// Not accessible in other files
const MyOtherVariable = 7;

In Meteor 1.3 and above, the recommended way of sharing code between files is via import/export, a newly developed feature in ES2015:

// Can be imported in other files
export const MyVariable = 5;

// Cannot be imported from other files
const MyOtherVariable = 7;

Here is how you would import it:

import { MyVariable } from '../my-file.js';

This is just a super basic description of the concept, we’ll have a complete guide about it when Meteor 1.3 ships.