Declare a const variable in javascript without initialization - javascript

In javascript, as per my understanding, we can declare variables with let and var keywords and assign it a value later.
var a;
a = 5;
But, when I try the same approach with const keyword it does not work.
const a;
Uncaught SyntaxError: Missing initializer in const declaration
I understand my question has a basic contradiction because const keywords are used for storing immutable variables. Therefore, a good coding practice may require it to be initialized while being declared.
However, I want to store global value in a const variable that is being fetched by an API. So, I was wondering if there is a way to assign a value to a pre-declared const variable in javascript?

const applies to the variable, not the value. You have to initialize them, because you can't assign them later -- that's the only difference they have. You can't have a variable that you can assign just once, but not reassign.
If the result is an object, you can declare the constant to hold an empty object, and then use Object.assign() to fill it in with the API response.
const result = {};
fetch(...).then(response => response.json()).then(data => Object.assign(result, data));

Have two ways to create a const with default value, 1 object with properties mutable, 2 array, as you can see bellow.
const a = {};
cosnt b = [];

I think you can not do that way . In JavaScript const variables must be assigned a value when they are declared:
Incorrect
const PI;
PI = 3.14159265359;
Correct
const PI = 3.14159265359;
For more reference you can take a look at this which gives you a better explanation
https://www.w3schools.com/js/js_const.asp

You can't do so, at least not in run-time. I suggest you consider using TypeScript, which has the readonly modifier which will help you protect your variable from being overwritten during compile-time.

Related

Is it possible to reassign const variable in javascript

Is it possible in JavaScript to reassign const variable;
In C++ we can cast variable to and from const, but is it something similar possible in JavaScript;
Here I ask about
const a = 1;
unconst(a);
a = "xyz";
a === "xyz" // true
Not object properties reassignments and array push/pop;
or
let a = 1;
const(a);
a = "xyz"; // error
a === 1 // true
a is const now, something like Object.freeze for objects
No, not with standard API. See also: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const
Constants are block-scoped, much like variables defined using the let statement. The value of a constant can't be changed through reassignment, and it can't be redeclared.
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.

Why does var allow duplicate declaration but why does const and let not allow duplicate declaration?

Why does var allow duplicate declaration but why does const and let not allow duplicate declaration?
var is allow duplicate declaration
xx=1;
xx=2;
console.log(xx+xx);//4
var xx=1;
var xx=2;
console.log(xx+xx);//4
But let and const does not allow duplicate deceleration
const yy=1;
const yy=2;
console.log(yy+yy);//Uncaught SyntaxError: Identifier 'yy' has already been declared",
let zz=1;
let zz=2;
console.log(zz+zz);//Uncaught SyntaxError: Identifier 'zz' has already been declared",
I saw something about that in here like,
Assuming strict mode, var will let you re-declare the same variable in the same scope. On the other hand, let will not.
But I want to know Why let and const doesn't allow re-declaration? and why var does? and How JavaScript handle these three type of deceleration ?
var
The var keyword was the only way to define variables until 2016*.
No matter where you write var x, the variable x is treated as if it were declared at the top of the enclosing scope (scope for var is "a function").
All declarations of the variable within the same scope are effectively talking about the same variable.
Here is an example... you might think that within the function we overwrite the outer name with fenton, and add Fenton to the inner variable...
var name = 'Ramesh';
function myFunc() {
name = 'fenton';
var name = 'Fenton';
alert(name);
}
myFunc();
alert(name);
In fact, it works just like this... the outer variable is not affected by the inner variable thanks to hoisting.
var name = 'Ramesh';
function myFunc() {
var name;
name = 'fenton';
name = 'Fenton';
alert(name);
}
myFunc();
alert(name);
Actually, you could also declare them implicitly by not using the var keyword at all, in which case they would be added to the global scope. Subtle bugs were often tracked to this.
let and const
Both let and const are block-scoped, not function-scoped. This makes them work like variables in most other C-like languages. It turns out this is just less confusing than function-scoped variables.
They are also both "more disciplined". They should be declared just once within a block.
The const keyword also disallows subsequent assignments - so you have to declare it with an assignment (i.e. you can't just write const x, you have to write const x = 'Fenton') - and you can't assign another value later.
Some people think this makes the value immutable, but this is a mistake as the value can mutate, as shown below:
const x = [];
// I can mutate even though I can't re-assign
x.push('Fenton');
// x is now ['Fenton']
Why Does it Matter?
If you want to avoid some of the more confusing aspects of var, such as multiple declarations all contributing to the same hoisted variable, and function-scope, you should use the newer const and let keywords.
I recommend using const as your default keyword, and upgrade it to let only in cases where you choose to allow re-assignment.
Unlike var, let is an ES2015 specification. The specification says:
Redeclaring the same variable within the same function or block scope raises a SyntaxError.
This is to improve scoping over vanilla var.
why does const and let not allow duplicate declaration?
There's a big difference between how c# or java (for example) handle duplicate variable names, where name collision returns a compilation error, and how it works in an interpreted language like js. Please, check the snippet below: The value of i isn't duplicated? Not really, still, in the function and block context the same variable name is referred as two different variables, depending on where those are declared.
function checkLetDuplication() {
let i = 'function scope';
for ( let i = 0 ; i < 3 ; i++ )
{
console.log('(for statement scope): inside the for loop i, equals: ', i);
}
console.log('("checkLetDuplication" function scope): outside the for loop i , equals: ', i);
}
checkLetDuplication();
Assuming you want to know whether this behavior is as per spec, check this 13.3.2
Within the scope of any VariableEnvironment a common BindingIdentifier
may appear in more than one VariableDeclaration but those declarations
collective define only one variable.
let and const are the recent editions, while var is probably as old as Javascript itself.
In old days Javascript code-base didn't used to be too big to bother about programming mistakes and most probably focus was to ensure that instead of reporting the error of re-declaration of variable JS engine should handle it.

Why Const is often used in object declaration while its properties could be changed? [duplicate]

This question already has answers here:
When to use const with objects in JavaScript?
(6 answers)
Closed 5 years ago.
my question is simple about Const. i have seen a lot places that devs prefer const over let and var while declaring object even its properties are mutable. Could somebody explain this?
const a = {};
a.name = "";
console.log(a.name);
Simply to prevent the object itself being overwritten or having its type changed. The constant will always be an object.
const a = {};
a = 'foo';
const b = {};
b = { foo: 'bar' };
Both will throw:
Uncaught TypeError: Assignment to constant variable.
It prevents a (in your example) from being assigned a different reference, but properties within the object are often needed to be changed as they convey the current state of the object instance.
A simply analogy, which is more correct here?
var me = "Scott";
const me = "Scott";
What should happen if this then happens?
me = you;
Let's forget the fact that, in real life, you can change you name if you really want to. In this case me should always and forever reference, well, me - "Scott" so const is the better declaration.
But, over my lifetime, characteristics of me will change, some that are out of my control and some that are in my control. So, while we don't want the me reference to change to reference a different object, aspects of the object that me does reference should be able to be changed:
const me = {};
me.height = "6' 1"; // Used to be 6' 3" back in the day!
But, if you needed a constant value to hold in an object, you could declare a private variable in a constructor function to do that.
function Me(height){
// Some aspects of this object will never change. They can be set up
// as private data:
const bloodType = "B+";
// Others are just properties:
this.height = height;
}
Or, you could continue to use an object literal, but you'd need to "lock down" certain properties so that become read-only. This is done with Object.defineProperty.
According to MDN
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 parameters) can be altered.

Javascript - how to declare namespace objects using new conventions

I am a big fan of latest programming conventions and latest additions to programming languages. Recently I read in Google Guidelines that we should use const and let instead of var.
Now in my project I have namespace object variables (if that's what they are called, correct me please if I am wrong) like this
var myObj = {
func1: {},
func2: {}
};
var myOtherObj = {
var1: 'foo',
var2: 'bar'
};
How should I name these objects now using the new conventions, with const or with let? I am confused because I don't know if these big objects change over time, or not...
const doesn't prevent objects from changing (said otherwise it doesn't freeze them). It prevents the value of variables to change.
For example you can still do
const myObj = {
func1: {},
func2: {}
};
and then
myObj.fun3 = function(){...
What you can't do with a variable declared with const (but which doesn't seem to be your will) is
myObj = {};
Modules are usually declared with const.
The general rule I try to follow is: const everywhere you can, let when you can't use const and var never.
In the case of your example, when you are defining objects (or in other cases arrays, etc.), I tend to define those with let to give a clear indication that either the variable reference could change or the contents inside.
const will not prevent properties of objects or elements in a list from being changed, so if you're unsure if thats going to happen, its best to use let in my opinion. It's more clear and could prevent confusion down the road.
If you really want a symbol that can't change value to refer to an object that is also immutable, you can do this:
const CONSTANT = Object.freeze({
a: "hello",
b: "world"
});
Also bear in mind that older platforms are still out there that won't support const and let (and probably Object.freeze() for that matter).

Why is my constant not pointing to new value

If i am not wrong, the pointer that the variable name is using cannot change in memory, but the thing the variable points to might change.
let name = "google";
const foo = name;
console.log(foo); //prints google
name = "yahoo";
console.log(foo); //prints google again instead of yahoo
Should it not print yahoo, as the variable name's value has been changed.. Can anyone explain me this.
Another example, where its changes...
const foo = [];
foo.push("test");
console.log(foo); // outputs ["test"]
I am getting confused here, can anyone explain me this.
Your first example uses an immutable string and the second uses a mutable object.
JS strings are immutable after being declared or created, so foo is not a reference to name's value, it points to the string. You're not changing the strings, you're pointing to a different one.
The array variable points to the object and continues pointing to the same object after it's been mutated. You're still pointing to the same object, however, since const is not deep.
This also highlights a common misunderstanding with JS' const, which functions more like Java's final than C++'s const. You are declaring a variable as const, not an instance of the object, so it only prevents you from reassigning to the variable, it does not prevent you from mutating the underlying object.
From MDN:
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.
This means that you can change the value assigned to a const, say by changing array or object, but cannot assign a new value to the const variable. E.g.:
Valid:
const a = [];
a.push(5);
console.log(a);
const b = {};
b['foo'] = 'bar';
console.log(b);
Invalid: This will throw error
const a = [];
a = [5];
console.log(a);
const b = {};
b = {'foo': 'bar'};
console.log(b);

Categories