Is it possible to change a const in a function? (JS) - javascript

I am trying to change a const to the preferred search engine (website linked below). Is it possible? If so, please provide a solution. Thanks!
The website: https://newtabb.gq
Website #2 (instant updates): https://newtabb.hyderite.repl.co
The code: https://replit.com/#Hyderite/newtabb (in script.js)
The code involved:
search.onclick = function() {searchQuery()};
function searchQuery() {
window.open(searchEngine + query);
}

Per the MDN Web Docs:
Constants are block-scoped, much like variables declared using the let keyword. The value of a constant can't be changed through reassignment (i.e. by using the assignment operator), and it can't be redeclared (i.e. through a variable declaration). However, if a constant is an object or array its properties or items can be updated or removed.
Per your code, the const is not an object or array so nothing about it can be changed. And if you wish to set a new value as a new variable, note you won't be able to use the same name (redeclaring it somewhere in your code).

Related

What does the term 'binding' mean in JS?

Please clarify for me what the term binding means in JavaScript. I've started to read the book 'Eloquent JS' and there are lots of occurrences of this word. Does it just mean variable? Here are few examples from the book:
So if you know that the property you are interested in is called color, you say value.color. If you want to extract the property named by the value held in the binding i, you say value[i].Property names are strings. They can be any string, but the dot notation works only with names that look like valid binding names.
Bindings can also be changeable or constant, but this is separate from the way their values behave. Even though number values don’t change, you can use a let binding to keep track of a changing number by changing the value the binding points at. Similarly, though a const binding to an object can itself not be changed and will continue to point at the same object, the contents of that object might change.
I've found out what it is (in this book in an earlier chapter). Here is the snippet:
How does a program keep an internal state? How does it remember things? We have seen how to produce new values from old values, but this does not change the old values, and the new value has to be immediately used or it will dissipate again. To catch and hold values, JavaScript provides a thing called a binding, or variable:
let caught = 5 * 5;
That’s a second kind of statement. The special word (keyword) let indicates that this sentence is going to define a binding. It is followed by the name of the binding and, if we want to immediately give it a value, by an = operator and an expression.
The previous statement creates a binding called caught and uses it to grab hold of the number that is produced by multiplying 5 by 5.
Binding is a general term to mean that your symbol or variable points to some location in memory. This is also illustrating the principle in JavaScript that even when you declare an object using const, you can still manipulate the properties of that object. Only the reference to the object itself cannot be redefined.
So you can't say myObj = {greeting: "Hello Stack Overflow"} and then myObj = someOtherObj. But you can say myObj.greeting = "Beep Boop"
Okay, let me clarify. The first question what is a binding:
A binding is a symbol, variable, constant, etc. that points to some literal value, or object in memory.
In reference to your book, it says:
const myObj = { color: blue }; // the property color is defined on this object
myObj["color"]; // => "blue" The color property can be accessed by passing in a string
myObj = anotherObj; // not allowed, you declared it with const
The reference or binding is to the object in memory and that cannot change because you declared this reference with const. But you can modify the properties of the object in memory. The object itself is mutable.
Any further discussion of bindings is a discussion on Lexical Scope.

Why does declaring a variable named values as an object returns type of function in Firefox

I have used var values = {}; in a JavaScript file. However when I test my application on Firefox typeof(values) returns function instead of object. This can easily be tested within Firefox console window. As this variable has been used many times in my application; changing it's name may not be a feasible solution. My questions are:
Is there a way to force this variable name as an object?
What other variable names should i be concerned in order to avoid this problem?
The problem is your assignment tries to change the read-only property window.values which is a function, a console utility.
You don't have such problem if you do it in an inner scope:
(function(){ var values = {}; console.log(typeof values) })()
The difference between Chrome and Firefox is that Chrome doesn't define this property as read-only.
That's just an artifact of the Firefox console, it doesn't affect your real code. If you use typeof values in your actual script code, you'll see that it's undefined (or object if you create it as shown in your question).
Firefox's console provides values as a means of seeing the values of an object:
>> values({foo: "bar"})
-> Array [ "bar" ]
There are other functions available in the Firefox console; they're documented here.
Chrome / Chromium has a bunch of them as well (including values), documented here.
Is there a way to force this variable name as an object?
In real script code, not the console, there's no problem using values. However, I suggest avoiding creating globals, since the global namespace is very crowded.
What other variable names should i be concerned in order to avoid this problem?
name and title are common ones people trip over. This is another reason not to use global variables. Instead, put your code in a scoping function:
(function() {
// Your code here
})();
Because by doing so in firefox, you're trying to override/re-assign the global read-only window object values which type is function
window.values // its a function
Chrome however doesnt treat values as a read-only object
In order to make it works as you wish in Firefox, you need to place it inside a function
function test() {
var values = {};
console.log(typeof values); // typeof: object
}

javascript How do I "dereference" a variable's content for use as a variable name?

I want to reduce the I/O overhead of fetching information from the server using XMLHttpRequest() or ActiveXObject(), as appropriate, by making a general-purpose function for doing the fetch which then stores the fetched data using sessionStorage.<variable>. The trouble is, I don't know in advance what the variable names all are, and I intentionally don't want to know.
I was thinking that if there is some way to "dereference" a variable, like we can easily do in BASH, for example, this would be trivial. For example, if the fetched data was in newData, and the name of the file it was fetched from is in dataFile, and if the dereference syntax was, say $(<variableName>), then one could write code like this to store and fetch the data:
//Store the data:
sessionStorage.$(dataFile) = newData;
//Fetch the data:
var storedData = sessionStorage.$(dataFile);
Get it? ... OK, now, how do I ACTUALLY do this?!
...The only other way around this I can see is VERY clumsy - make arrays, one with name, another with values - there MUST be an easier way! TIA.
As always, it is good to visit the docs first. There you can see, that sessionStorage (like localStorage or Map) has no properties at all (except a hidden property pointing to internal memory but thats another thing), but rather makes the data available through its get or set methods:
sessionStorage.set("a name", "a value");
However the session/localStorage provides also global getters/setters, so in theory one can do:
sessionStorage.name = "value";
If the keys name is dynamic one could use bracket notation:
sessionStorage[aName] = aValue;
However, they havent it even mentioned in the docs, so this feature is neither widely supported nor a good coding style.
Try this. Not exactly sure I followed your question clearly but I would try this if you are having issues using the variable name as string within your other code.
var_param = GET_YOUR_VAR_SOMEHOW; // strip your params as needed
let f1 = { getVarName:var_param.toString()} // object = to f2
let f2 = 'getVarName'; // string = to f1 key
var storedData = sessionStorage.$(f1[f2]); // result of f1[f2] should be your incoming var string, de-referenced from any content.

JavaScript - Functions as objects

The concept of functions being objects in JavaScript would be ok with me if I could understand the following question. I have searched around and looked into the javascript engine to try and find the answer, but no explanation I've found so far sits well in my mind...
An object like the one below is understandably layed out in a hash map type of construct.
var person = {
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"
};
However, to say this is also an object is where I get stuck:
var name = function () {
alert ('name');
}
In terms of memory, how is this function stored?
Are the statements inside the "hash map" of a function layed out in an execute order? So each property is called upon after the other?
I'm probably missing something or visualising something wrong.
Thanks.
P.S
To clear up question 2,
Say I have an if statement inside my function... will that be stored in a property accessible through one of its properties?
Every object in javascript has properties (key-value pairs identified by strings or symbols) and it has internal slots.
The function object name is stored in the same format as the person object, but their internal slots differ.
person's properties are firstName, lastName, age and eyeColor, each holding the respective primitive value
person's internal slots are (amongst others):
[[prototype]], pointing to Object.prototype
name's properties are name, prototype and length (as typical for Function instances)
name's internal slots are (amongst others):
[[prototype]], pointing to Function.prototype
[[ECMAScriptCode]], pointing to the code of the function
[[Environment]], pointing to the scope the closure was created in
Disclaimer: That's only how it behaves, engines may implement this however they want. Still, it serves well as a mental model, and it's important to understand that objects have a layer below the publicly visible properties.
Functions are objects, in that they can have properties and methods. Unlike objects, they can also be called and will always return a result.
Note that the ECMAScript (i.e. JavaScript) language specification describes how Function objects should behave rather than underlying implementation, so the in-memory representation of the object will depend on implementation.
Regarding 2: Note that the full text of a Function might be stored in the functionBody property, however the body of a Function does not have to be JavaScript. It could be native code, for example, that is not meaningful to return in a string.
If you just want to do regular JavaScript coding, I don't think you really need to worry about how the function is stored by the browser or server or whatever. I do think you are misunderstanding the object-nature of a function. The lines of code inside the function are not individual parts of a hash map. Rather (and this only begins to touch on the concept), a function can have properties with names and values just like a regular object can have such properties. The following code demonstrates this.
var myFunc = function() {
var x = "hello".toUpperCase();
document.write('<p>' + x + '</p>');
};
myFunc.favoriteColor = "red";
myFunc(); // runs the function and shows the text "hello"
document.write("<p>" + myFunc.favoriteColor + "</p>"); // shows the text "red"
The answer to 1. is: It depends on the implementation.
The 2nd question doesn't make any sense.
I think you are looking at the syntax, and assuming that because the way data is declared, and the way functions are declared, that a function can be treated as data in the language.
This is not the case.
There are languages where this IS the case. Lisps and Prolog being the most common examples. see:
https://en.wikipedia.org/wiki/Homoiconicity

Javascript setting variable names by variables [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript Variable Variables
Please take a look at code below
var selected_id=1;
resetVar("selected");
function resetVar(foo){
foo+"_id"=0; // I want to set selected_id into 0
}​​​​​
Is that possible? Any suggestion?
If your variables are global variables, then they are implicitly properties of the window object and you can reference them as properties of the window object like this:
function resetVar(foo){
window[foo + "_id"] = 0;
}​​​​​
var selected_id = 1;
resetVar("selected");
If your variables are not global variables, then you will need to make them properties of some known object so that you can use this same technique.
In general, this is usually a bad programming idea and we often see this question where there are better ways to handle the situation. You don't disclose what the overall situation is so we can't advise very specifically, but you should usually be using properties on a known object directly or you should be using an array to hold several related values in the array or you should just be referencing the variable directly.
if selected is a global variable:
function resetVar(foo){
window[foo+"_id"] = 0;
}​​​​​
You can invoke functions using square bracket notation on the object which owns the method (in your case, the global, window object).
window['selected_id'] = value
This is a "solution" often proposed by beginners (which is not a bad thing, everyone starts somewhere). The answer is; don't do that, use an array (or some other collection).
Using variable names to determine program logic is a terrible idea that will inevitably lead to messy, unmaintainable code. Changing the name of a varibale should not change your program's logic. Instead, group obbjects into a collection, using a key into the collection if needed, or simply the index.

Categories