Is it possible to reassign const variable in javascript - 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.

Related

Wiered behaviour with object declared with const [duplicate]

This question already has answers here:
Why can I change a constant object in javascript
(12 answers)
Closed 1 year ago.
I have been working on some exercise with let and const and found something interesting with const along with objects assignments.
As per definition: In JavaScript, const means that the identifier can’t be reassigned.
const numConst = 20;
numConst = 40;
console.log("numConst", numConst);
Uncaught TypeError: Assignment to constant variable.
Whereas when I try to modify the object declared with const, it is allowed:
const person = { name: "test", age: 20 };
person.age = 40;
console.log("person.age", person.age); // outputs: person.age 40
Why does const behave differently with object?
https://www.w3schools.com/JS/js_const.asp
The keyword const is a little misleading.
It does NOT define a constant value. It defines a constant reference to a value.
Because of this, we cannot change constant primitive values, but we can change the properties of constant objects.
const a = {foo: 'bar'}; defines a new object (thus a new reference). this reference will be stored in a.
when invoking a = {bar: 'foo'} later, you tell the program, to change the reference a. This is not allowed due to the const constraint.
On the other hand, a.bar = 'foo' will modify the value refenreced by a, but not the reference itself.
You assign an object to const which is reference type. Now if you add new keys to object or modifiy the existing values of key you can do so because person preserving the reference of that object and by using person.age you are changing the value of object not the reference.
But if you try to assign a new reference to person like this
const person = { name: 'test', age: 20 };
person = { name: 'hi', age: 10 };
console.log(person);
you will get error Uncaught TypeError: Assignment to constant variable.
Both arrays and objects are reference type and by using same reference you can add or remove keys from object or can change values. Same as using arrays you can push new values or can pop but can't assign a new reference to that const.
const behave differently for object because when you create something like:
const person = {name:"test",age:20};
here person holds the reference (memory address) in it and when you change some data in object its reference is not changed but the key:value pair is changed that's the reason it doesn't show error in case of objects.

Declare a const variable in javascript without initialization

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.

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.

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);

Passing ECMAScript 6 const as Function Argument

I've been reading a lot about ES6 lately and decied to give it a try (using Babel). I'm a little confused with new variable declarations let and const.
I understood how scope differs from var; and that const is a permanent reference to a value (and not a constant value itself!).
Q: What if I pass const variable to a function call? Will the receiving function be able to change the value / reference? Why? Why not?
The semantics of a parameter being passed to a function is completely independent of how that parameter was declared (whether using var, let, or const). What is passed to the function is merely some value. The receiving function has no visibility into how or where the value was derived, including, if it is a variable, how that variable was declared. It merely sees the value that was passed in. The new let and const keywords have no relevance to this behavior.
It is the source of some confusion that given the value of an array or object, that array or object can be manipulated. So I can do the following:
const a = {};
a.x = 1;
const in the above makes a itself a constant within its scope, so it cannot be re-declared or re-assigned, but it in no way prevents the internal structure of a from being changed, in this case by adding a property x.
Similarly, in a parameter-passing context:
function func(obj) { obj.x = 1; }
const a = {};
func(a);
Here, func receives the value of a as obj, but with that value it may access/change the internals of the object.
Of possible interest: How to make function parameter constant in JavaScript?.
As you can see here and here that the const declaration creates a read-only named constant i.e. not a named reference.
Now, if you pass a const to a function you are actually creating a new scope:
You are passing the const "by value" and the local function variable will get the value of the const and not the reference to it as in any non immutable object (like strings).
You will be able to change the local var but not the original const.
When you pass a variable with a primitive type (string, number, etc.) as argument, you pass the variable by value. When it's a reference to an object or array, you pass by reference, but the function argument is another variable, not const (mutable), that has the same reference.
It means that the argument variable has the same reference and can make changes (like adding or removing data in the array) that will impact the original variable, but if the argument variable changes it's reference (like argument = {}), the changes will not reflect to the original variable (even if the original one is not const).
Example:
const str = 'string';
function changeToNumber(argument) {
argument = 10;
}
changeToNumber(str);
console.log(str); // 'string'
const obj = { prop: 1 };
let notConstObj = { prop: 1 };
function changeToArray(argument) {
argument = [10];
}
changeToArray(obj);
console.log(obj); // '{ prop: 1 }'
changeToArray(notConstObj);
console.log(notConstObj); // '{ prop: 1 }'
function modifyObj(argument) {
argument.prop2 = 10;
}
modifyObj(obj);
console.log(obj); // '{ prop: 1, prop2: 10 }'

Categories