This question already has answers here:
What characters are valid for JavaScript variable names?
(12 answers)
Closed 7 years ago.
I am coding a scientific calculator and I need some help:
function √(in){
return Math.sqrt();
}
// throws an error
var √ = function(in){
return Math.sqrt();
}
// also throws an error
var √ = "sqrt";
√randomSqNum = 100,
√random = {sqrt:4,cubert:8},
√sqNum = ["0","1","4","9","16","25"],
√null = null,
√undefined = undefined;
They all throw an error!
Please explain why they throw an error.
Also, Is there a way around this?
In Javascript, variable names must begin with a letter, _ or $. More information here:
http://www.w3schools.com/js/js_variables.asp
JavaScript follows annex 31 of the unicode standard regarding identifier names.
I assume you are using U+221A as character. As you can see from the linked page, it can neither be used at the beginning of an identifier nor within it:
(likely because it is not even a letter).
Compare that to π, which is a letter and which can be used in an identifier name.
Also, Is there a way around this?
No. However, you can always try to find letters that look similar.
You cannot use it directly as a name, but you can use it as key.
var f={}
f["√"] = Math.sqrt
alert(f["√"](5))
In such way you can define +-*/ and many other funcions.
f["+"] = function(a){
return a.reduce(function(p,v){
return p+v
},0)
}
And when you have a parsed statement tree in form {o:fn,a:[s1,...,sn]} where fn is function name and s1,...,sn are subtrees or values, then you can simply get the result:
function calc(st){
return (typeof st == 'object')?f[st.o].apply(null,st.a.map(calc)):st
}
Related
This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
What is the difference between object keys with quotes and without quotes?
(5 answers)
Closed 3 years ago.
I'm currently trying to learn JavaScript. I have some experience with Java and C++. I've been trying to find a clear cut and specific explanation of accessing and creating properties in JavaScript and have been unable to find one. Some question I have about objects:
var myObj = {
firstName: "Vinnie",
lastName: "Glaser"
}
1.) When defining objects, sometimes people put quotations around the key and sometimes they don't. What significance does this have? If there are no quotations around the key value is it still considered a string?
2.) When accessing properties of objects, sometimes people put quotations around the key and sometimes not. What is the significance of this?
3.) What practical differences are there between myObj[key] and myObj.key? There have been a few scenarios in which one is necessary over the other but I'm not sure why.
4.)
myObj[fullName] = myObj[firstName] + " " + myObj[lastName];
Why doesn't this work?
Thank you for the help.
1.) When defining objects, sometimes people put quotations around the key and sometimes they don't. What significance does this have? If
there are no quotations around the key value is it still considered a
string?
2.) When accessing properties of objects, sometimes people put quotations around the key and sometimes not. What is the significance
of this?
All valid keys are interpreted by the system as strings regardless of whether they are in quotes or not and regardless of what the key actually is. Even a key of 1 would be processed as "1" and you can see this in your browser's debugger, so it's not about making the key a string or not. It's simply about whether the key name is valid syntax without them. For example, most people would say that a property (key) name can't contain spaces:
let obj = {
my property : "foo"
};
But, that's not true. It's just the un-quoted key names that contain a space is invalid syntax. You can do it with quotes:
let obj = {
"my property" : "foo"
};
// Then, you access the property through array-like syntax
console.log(obj["my property"]);
3.) What practical differences are there between myObj[key] and myObj.key? There have been a few scenarios in which one is necessary
over the other but I'm not sure why.
Syntax. In the above example, it would be invalid syntax to try either of these:
obj.my property
obj."my property"
But, if you access keys using array-like syntax, you would have to pass in the index and in that case strings are legal syntax:
obj["my property"]
4.) Why doesn't this work:
myObj[fullName] = myObj[firstName] + " " + myObj[lastName];
Without quotes around the index values, the system believes that what you are passing are variables, so it attempts to get the values out of the variables. It would work if the values you are passing in were declared variables that have values and those values mapped to existing keys in the object.
let myObj = {
full : null,
first : "Scott",
last : "Marcus"
};
let fullName = "full";
let firstName = "first";
let lastName = "last";
myObj[fullName] = myObj[firstName] + " " + myObj[lastName];
console.log(myObj[fullName]);
This question already has answers here:
How do I replace a character at a particular index in JavaScript?
(30 answers)
Closed 6 years ago.
This is related to the arrays in Javascript, which I am trying to use in a complex logic.
Consider the following code:
a['a1'] = 'AJA'
We know that, this is same as a.a1 = 'AJA' (provided proper definitions were given).
So, if we go ahead and interpret this:
console.log(a.a1[0])
console.log(a.a1[1])
console.log(a.a1[2])
console.log(a.a1)
It logs :
A
J
A
AJA
Now, all I need is to assign a new character at the 4th position.
When I try a[a1][3] = 'Y' or a.a1[3] = 'Y' and then try console.log(a.a1), It still displays AJA instead of AJAY.
I know that we can do this using string concatenation, i.e.
a['a1'] = a['a1'] + 'Y' and get this accomplished.
But why wasn't the first method working? By what other ways can do this?
Strings are immutable. It means that if you create a string, you can't modify it anymore. So your a1 doesn't know anything about 4th character.
You can see this example. I try to change the second char of the already created string, but it will not be changed anymore.
let a = {};
a['a1'] = 'AJA';
a.a1[1] = 'A';
console.log(a.a1);
For more you can see MDN Documentation
As I know a[a1][3] or a.a1[3] is a string variable, you can treat it as:
var s = 'ss';
When you evaluate s[0] you'll get a string value. So when you assign any string value to s, you'll not get 'ss' + anyvalue but anyvalue instead. :)
This question already has answers here:
Calling member function of number literal
(3 answers)
Closed 6 years ago.
I have included custom Number.prototype in my JS as below:
Number.prototype.isBetween = function (first, last) {
return (first < last ? this >= first && this <= last : this >= last && this <= first);
};
This is working as expected with below code:
var a = 40;
a.isBetween(10,50)
Result :
true
But when i try to execute as below, it is throwing an error:
40.isBetween(10,50)
Result :
Uncaught SyntaxError: Invalid or unexpected token
How to make this(40.isBetween(10,50)) work?
You can wrap the number in parentheses to solve this.
(40).isBetween(10,50)
// => true
Without the parentheses, there is ambiguity in the grammar that the language parser intentionally avoids by throwing an error.
For details and other solutions, see answers to this question: Calling the toFixed method on a number literal
This question already has answers here:
Do common JavaScript implementations use string interning?
(3 answers)
Closed 7 years ago.
In some languages, frequently used strings are defined as variables/constants, which are called instead of literal strings. Is this the same with JavaScript? In particular, I have frequent use of the string 'none'. Instead of writing the literal 'none' everywhere in the code, would it improve performance if I define:
var none = 'none';
and use none everywhere in the code? Or, is there a way to intern a literal string expression so that it is evaluated only once?
Literal strings are automatically interned by most Javascript compilers. So var a = 'hello' and var b = 'hello' will likely already be pointing at the same copy of the 'hello' string in memory, no need for further optimization on your part.
The only way to make sure different string objects are created for the same string value is by defining each one via the String global object, i.e.:
var a = new String('hello');
var b = new String('hello');
This question already has an answer here:
Accessing a JSON property (String) using a variable
(1 answer)
Closed 8 years ago.
I want to use a string as a JSON property in JavaScript.
var knights = {
'phrases': 'Ni!'
};
var x = 'phrases';
console.log(knights.x); // Doesn't log "Ni!"
When I run this code, it obviously doesn't work because it interprets "x" and not the contents of the variable "x".
The full code in context on pastebin: http://pastebin.com/bMQJ9EDf
Is there an easy solution to this?
knights.x looks for a property named x. You want knights[x], which is equivalent to knights['phrases'] == knights.phrases.
Full code (fixing a couple of typos in your example):
var knights = {
"phrases": "Ni!"
};
var x = 'phrases';
console.log(knights[x]); // logs Ni!
Try this to access using variables having string values
kinghts[x]
Basically this is trick
kinghts[x]==knighted["phrases"]==knighted.phrases.
knights.x will get a key named x, So it'll return undefined here.
knights.x is the same as knights['x'] - retrieving a property under the key x. It's not accessing the variable x and substituting in the value. Instead, you want knights[x] which is the equivalent of knights['phrases']