Why can’t name the variable const, but in objects can [duplicate] - javascript

This question already has answers here:
Using reserved words as property names, revisited
(4 answers)
Closed 3 years ago.
I wrote.
let const = 10;
and got error.and for objects everything works
let x = {const:10}
What is the difference.

Variables can be used in the same places as you can use the const keyword. If you could use const as a variable name it would be hard to distinguish between the two.
That is not the case for property names; the syntax will always be clear that it refers to a property name.

const is a reserved keyword you cannot use as variable name, so the first one is invalid syntax,
let const = 10
In second example you're using const as key which can be any string
let x = {const:10}
console.log(x)

Related

How do I fill a new array with n distinct empty arrays, in a concise one-line initialization statement? [duplicate]

This question already has answers here:
How do you easily create empty matrices javascript?
(17 answers)
fill an array with arrays programmatically
(5 answers)
Array.prototype.fill() with object passes reference and not new instance
(7 answers)
Array.fill(Array) creates copies by references not by value [duplicate]
(3 answers)
Closed 1 year ago.
Here is where I am stuck. I want to take this statement and revise it in a manner that the empty array I fill (which I surmise might not work with dynamic values), will initialize bucket to the n distinct empty arrays.
How do I do this? Is there a way to make this fill method behave in the intended manner?
let radix = 10;
let badBucket = [...Array(radix).fill([])];
let goodBucket = JSON.parse(JSON.stringify([...Array(radix).fill([])]));
badBucket[3].push(33);
goodBucket[3].push(33);
console.log(JSON.stringify(badBucket));
console.log(JSON.stringify(goodBucket));
You can use the callback function of Array.from.
let length = 5;
let res = Array.from({length}, _=>[]);
console.log(res);
Try:
let radix = 10;
let bucket = [...Array(radix)].map(e=>[])
bucket[0].push(1)
console.log(JSON.stringify(bucket));

Why javascript indexOf method give me wrong output [duplicate]

This question already has answers here:
Using the variable "name" doesn't work with a JS object
(4 answers)
When using object destructuring assignment, why is a property "name" cast to string? [duplicate]
(1 answer)
Closed 1 year ago.
If i us "var" to declare array given as below. Why give me 6
var name = ['Rohan', 'Google', 'Student'];
console.log(name.indexOf('Google'));
Otput is 6
If i use "let" to declare array give me right answer why
let name = ['Rohan', 'Google', 'Student'];
console.log(name.indexOf('Google'));
Otput is 1
Instead of naming your variable as name change it to some other name and you will get a right result.
var myArray = ['Rohan', 'Google', 'Student'];
console.log(myArray.indexOf('Google'));
The reason is there is some global variable called name whose result is being shown (If you check developer console and search window.name you can know what that variable is).
var has global scope in this case pointing to window object.
And in case of let name, we should know that let has local scope within the context so this time name points to your array not global name. Infact ES6 introduced let, const to avoid global spacing issue that we were facing with var

Behind the scene working of Javascript const for primitive vs objects? [duplicate]

This question already has answers here:
Why can I change a constant object in javascript
(12 answers)
JavaScript ES6 `const a = {}` is mutable. Why? [duplicate]
(2 answers)
Closed 1 year ago.
I came across this interesting concept where const behave differently for number, string, Boolean vs Object, arrays.
const num1 = 10
num1 = 20 //throws error
const arr1 = [1,2,3,4]
arr1.push(5) //works
arr1.pop() //works
arr1[2] = 7 //works
arr1 = [2,3] //throws error
For array & objects it allows change in value but throws error in assignment. Is it mean, there is no advantage of declaring object or array as const, as you can change all values anytime?
If anyone can explain, I would like to know, how, behind the scene, const works?
The const declaration creates a read-only reference to a value.
The value it holds is still immutable. Both array and object are holding some values. Those values and properties can be changed but same variable identifier cannot be reassigned.
Here arr1 is an variable identifier
const arr1 = [1,2,3,4]
arr1.push(5) //works // changing the value
arr1.pop() //works //changing the value
arr1[2] = 7 //works // changing the value
Here arr1 got reassigned so it is throwing an error
arr1 = [2,3] //throws error // reassigning the same variable

Struggling with Javascript Object Array adding keys [duplicate]

This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 5 years ago.
I have this snippet of code:
var arrLiteData = [];
for(ii=0;ii<10;ii++)
{
arrLiteData.push({ii:{"field1":100,"field2":ii}});
}
...but instead of ii taking the increasing numeric value of ii, the array just holds the actual variable name, like this:
[{"ii":{"field1":100,"field2":0}},{"ii":{"field1":100,"field2":1}}...etc, etc...
What am I doing wrong?
Many thanks.
Quotes are optional for javascript object keys, so
{ii:{"field1":100,"field2":ii}} is the same as
{"ii":{"field1":100,"field2":ii}} or even
{ii:{field1:100,field2:ii}}. They are just need if you have non alphanumeric characters.
To solve this you could either use a computed key if you're transpiling your code or targeting recent navigators:
{[ii]:{"field1":100,"field2":ii}}
Or build the object in two steps:
var arrLiteData = [];
for(ii=0;ii<10;ii++)
{
var obj = {};
obj[ii] = {"field1":100,"field2":ii};
arrLiteData.push(obj);
}

Use a variable inside a dictionary (associative array) in javascript [duplicate]

This question already has answers here:
Is it possible to define a dynamically named property using object literal in JavaScript? [duplicate]
(7 answers)
Closed 8 years ago.
I have this particular script which uses a javascript dictonary
var z= 'Bingo';
var fruit={ 'Bingo' :1};
var fruit2={ z :1};
alert(fruit[z]);
alert(fruit2[z]);
alert(fruit2['z']);
The first alert gives the expected value 1. However, the second alert gives the alert value as "undefined" and third alert gives the output as 1. Is there a way to use a variable inside a dictionary, ie. can we specify the javascript interpreter to read z as a variable rather than as string 'z'?
Thanks!
Yes, you can do this easily, but not inside an object literal. Property names in object literals are taken literally. They are not variable names. JavaScript quotes them implicitly if you don't quote them.
For example, these two object literals are the same:
{ a: 1 }
{ 'a': 1 }
To use a variable, you need to use [] notation outside an object literal:
var z = 'Bingo';
var fruit2 = {};
fruit2[z] = 1;

Categories