Custom Number.prototype working with variable but NOT working directly with number [duplicate] - javascript

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

Related

What does "?." (dot after questiion mark) mean in JS [duplicate]

This question already has an answer here:
What does this symbol mean in JavaScript?
(1 answer)
Closed 2 years ago.
I stumbled upon the "?." syntax in another SO question. Something like this -
console.log(x?.y?.z);
What does it do?
This is called Optional Chaining.
It allows to use the property chaining without having to validate properties in each level. It short circuits property evaluation without raising exceptions - thus avoiding the "Cannot read X of undefined" error.
let o = {p: {q: 'foo'}};
try {
console.log('Trying to access the property x');
console.log(o.x.y);
}
catch(e) {
console.log('That was an error');
}
console.log('Trying to access the property x with Optional Chaining');
console.log(o?.x?.y);
Optional chaining more use cases
With function calls
let result = someInterface.customMethod?.();
With expressions
let nestedProp = obj?.['prop' + 'Name'];
With array elements
let arrayItem = arr?.[42];
ECMAScript Draft

Why 1["foo"] returns undefined instead of an error? [duplicate]

This question already has answers here:
How and why does 'a'['toUpperCase']() in JavaScript work?
(12 answers)
Why is 0[0] syntactically valid?
(7 answers)
Closed 4 years ago.
Today I came accross a strange thing in Javascript.
When in Chrome console if I execute :
> 1["foo"]
Chrome console returns :
undefined
I was expecting an error though. How is it possible? I fall on that by studying the underscore.js (an old version) invoke method that seems to use that JavaScript property:
// Invoke a method (with arguments) on every item in a collection.
_.invoke = function(obj, method) {
var args = slice.call(arguments, 2);
var isFunc = _.isFunction(method);
return _.map(obj, function(value) {
var func = isFunc ? method : value[method];
return func == null ? func : func.apply(value, args);
});
};
As you can see, value could be a number and if 1["foo"] was raising an error, that code would be unsafe as I could do the following by mistake:
var a = {'foo' : 1}
_.invoke(a, 'foo'}
Everything, even primitives, are essentially objects and can have members (properties, methods, etc). All the code in question is doing is attempting to find a member on 1 with the name foo which is not found so undefined is returned.

What is the Javascript equivalent of writing 'If not" [duplicate]

This question already has answers here:
Best way to find if an item is in a JavaScript array? [duplicate]
(8 answers)
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 6 years ago.
Python programmer here.
I don't know how to write this. I tried using 'if !in' and '!if in', but I don't know how. Tried to Google it but got no results.
The correct syntax is
if(!condition){
expression();
}
Note that you need parenthesis around the condition.
#plalx wants a formal definition, and here you go:
IfStatement:
if(Expression) Statement else Statement
if(Expression) Statement
In case of any ambiguity the else would be matched with the nearest if.
If you have some value:
var excludeMe = "something unwanted";
Then you can use the following if statement:
if(myTestCase !== excludeMe) { //do something...}
Keep in mind that != does not check type and !== does check type. So, 1 != "1" is false and 1 !== "1" is true.

Why can't I do 1.toString() but I can do var a = 1; a.toString() [duplicate]

This question already has answers here:
Usage of toString in JavaScript [duplicate]
(3 answers)
Closed 6 years ago.
When I do
1.toSting()
I get an error, but
// javascript
var a = 1;
// or c#
int a = 1
a.toString()
works. Why is it that when a number gets assigned to a variable, it get some special functions?
The . is interpreted as you want a decimal/floating-point literal, not invoking a member.
You can do this in JavaScript
// Option 1
(1).toString();
// Option 2
1.0.toString();
// Option 3
1..toString();
In C#, it appears your only option is (1).ToString(), but the lexer might be smart enough not to need them.

Why is √ is not allowed as a objectName/stringName/functionName/NumberName? [duplicate]

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
}

Categories