What is the purpose of a plus symbol before a variable? - javascript

What does the +d in
function addMonths(d, n, keepTime) {
if (+d) {
mean?

The + operator returns the numeric representation of the object. So in your particular case, it would appear to be predicating the if on whether or not d is a non-zero number.
Reference here. And, as pointed out in comments, here.

Operator + is a unary operator which converts the value to a number. Below is a table with corresponding results of using this operator for different values.
+----------------------------+-----------+
| Value | + (Value) |
+----------------------------+-----------+
| 1 | 1 |
| '-1' | -1 |
| '3.14' | 3.14 |
| '3' | 3 |
| '0xAA' | 170 |
| true | 1 |
| false | 0 |
| null | 0 |
| 'Infinity' | Infinity |
| 'infinity' | NaN |
| '10a' | NaN |
| undefined | NaN |
| ['Apple'] | NaN |
| function(val){ return val }| NaN |
+----------------------------+-----------+
Operator + returns a value for objects which have implemented method valueOf.
let something = {
valueOf: function () {
return 25;
}
};
console.log(+something);

It is a unary "+" operator which yields a numeric expression. It would be the same as d*1, I believe.

As explained in other answers it converts the variable to a number. Specially useful when d can be either a number or a string that evaluates to a number.
Example (using the addMonths function in the question):
addMonths(34,1,true);
addMonths("34",1,true);
then the +d will evaluate to a number in all cases. Thus avoiding the need to check for the type and take different code paths depending on whether d is a number, a function or a string that can be converted to a number.

Related

How to specify type of index of enum in typescript

Consider the following example:
enum Color {
Green = "green",
Red = "red"
}
let index : keyof Color
index = "Green"
console.log(Color[index])
Error
Type '"Green"' is not assignable to type 'number | "toString" | "charAt" | "charCodeAt" | "concat" | "indexOf" | "lastIndexOf" | "localeCompare" | "match" | "replace" | "search" | "slice" | "split" | "substring" | "toLowerCase" | ... 27 more ... | "padEnd"'.
Element implicitly has an 'any' type because expression of type 'number | "toString" | "charAt" | "charCodeAt" | "concat" | "indexOf" | "lastIndexOf" | "localeCompare" | "match" | "replace" | "search" | "slice" | "split" | "substring" | "toLowerCase" | ... 27 more ... | "padEnd"' can't be used to index type 'typeof Color'. No index signature with a parameter of type 'number' was found on type 'typeof Color'.
The index variable has to be string version of keys of enum Color.
How do I specify the type of index variable?
You should be using let index: keyof typeof Color, because Color is actually an object (a dictionary of sorts), so you will need to get its type first using typeof. For an in-depth explanation on what keyof and typeof does, there's an excellent question and thread that explains it.
enum Color {
Green = "green",
Red = "red"
}
let index: keyof typeof Color;
index = "Green"
console.log(Color[index])
See working example on TypeScript Playground.

A definition of the ^ operation in javascript [duplicate]

This question already has an answer here:
What does this symbol mean in JavaScript?
(1 answer)
Closed 3 years ago.
Can't seem to find a definition anywhere.
Typing into the console I can see...
5^4 = 1
5^3 = 6
5^2 = 7
Any ideas why?
It's a bitwise operation, ^ specifically does a XOR operation on the numbers.
XOR truth table
+-------------------+
| a | b | a ^ b |
+-------------------+
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
+-------------------+
00001001 -> 5
00001000 -> 4
--------
00000001 -> 1
00001001 -> 5
00000011 -> 3
--------
00001010 -> 6
00001001 -> 5
00000010 -> 2
--------
00001011 -> 7

"+" before variable in node.js / nuxt [duplicate]

What does the +d in
function addMonths(d, n, keepTime) {
if (+d) {
mean?
The + operator returns the numeric representation of the object. So in your particular case, it would appear to be predicating the if on whether or not d is a non-zero number.
Reference here. And, as pointed out in comments, here.
Operator + is a unary operator which converts the value to a number. Below is a table with corresponding results of using this operator for different values.
+----------------------------+-----------+
| Value | + (Value) |
+----------------------------+-----------+
| 1 | 1 |
| '-1' | -1 |
| '3.14' | 3.14 |
| '3' | 3 |
| '0xAA' | 170 |
| true | 1 |
| false | 0 |
| null | 0 |
| 'Infinity' | Infinity |
| 'infinity' | NaN |
| '10a' | NaN |
| undefined | NaN |
| ['Apple'] | NaN |
| function(val){ return val }| NaN |
+----------------------------+-----------+
Operator + returns a value for objects which have implemented method valueOf.
let something = {
valueOf: function () {
return 25;
}
};
console.log(+something);
It is a unary "+" operator which yields a numeric expression. It would be the same as d*1, I believe.
As explained in other answers it converts the variable to a number. Specially useful when d can be either a number or a string that evaluates to a number.
Example (using the addMonths function in the question):
addMonths(34,1,true);
addMonths("34",1,true);
then the +d will evaluate to a number in all cases. Thus avoiding the need to check for the type and take different code paths depending on whether d is a number, a function or a string that can be converted to a number.

Write Shortage of if-else statement with two cases in one line

There is a javascript expression that assigns name variable to renamed variable.
It is always the same with one exclusion:
renamed = name == 'John' ? 'Johnny' : name;
However, I want two exclusions:
rename John to Johny
rename Alex to Alexander
All other names are assigned with no changes.
Is it possible to write this expression in one string?
renamed = (name == 'John' || name == 'Alex') ? <____> : name;
I need it to be done in one string.
Thank you.
(name === 'John' && 'Johny') || (name === 'Alex' && 'Alexander') || name;
If name is John, then it goes to the next part in the && expression and returns Johny.
If name is Alex, then the like in the first case returns Alexander.
If neither of them is true, then return the name as it is.
Demo
This solution works because, in JavaScript, && operator evaluates the expression in the left and if it is falsy then the value will be returned and the right hand side expression will not be evaluated at all.
If the expression in the left evaluates to be Truthy, then the expression on the right side will be evaluated and the result will be returned as it is. For example
console.log(1 && 2);
# 2
console.log(0 && 2);
# 0
It first evaluates 1, it is Truthy so it 2 is evaluated and the value is returned. That is why it prints 2.
In the second case, 0 is evaluated to be Falsy. So, it is returned immediately. That is why it prints 0.
The same way
console.log("John" && "Johny");
# Johny
John will be evaluated to be Truthy and so Johny will also be evaluated and returned. That is why we get Johny.
As per ECMA 5.1 Standard, Truthiness of an object will be decided, as per the following table
+-----------------------------------------------------------------------+
| Argument Type | Result |
|:--------------|------------------------------------------------------:|
| Undefined | false |
|---------------|-------------------------------------------------------|
| Null | false |
|---------------|-------------------------------------------------------|
| Boolean | The result equals the input argument (no conversion). |
|---------------|-------------------------------------------------------|
| Number | The result is false if the argument is +0, −0, or NaN;|
| | otherwise the result is true. |
|---------------|-------------------------------------------------------|
| String | The result is false if the argument is the empty |
| | String (its length is zero); otherwise the result is |
| | true. |
|---------------|-------------------------------------------------------|
| Object | true |
+-----------------------------------------------------------------------+
Note: The last line, Object, which includes both objects and Arrays.
renamed = (name == 'john') ? 'johney': (name == 'alex'? 'alexander' : name);
you can try this:
renamed = (name == 'John' ? 'Johnny' : (name == 'Alex' ? 'Alexander' : name));

JavaScript if(x) vs if(x==true)

In JavaScript , in which cases the following statements won't be logically equal ?
if(x){}
and
if(x==true){}
Thanks
They are not at all equal.
if (x)
checks if x is Truthy where as the later checks if the Boolean value of x is true.
For example,
var x = {};
if (x) {
console.log("Truthy");
}
if (x == true) {
console.log("Equal to true");
}
Not only an object, any string (except an empty string), any number (except 0 (because 0 is Falsy) and 1) will be considered as Truthy, but they will not be equal to true.
As per ECMA 5.1 Standards, in if (x), Truthiness of x will be decided, as per the following table
+-----------------------------------------------------------------------+
| Argument Type | Result |
|:--------------|------------------------------------------------------:|
| Undefined | false |
|---------------|-------------------------------------------------------|
| Null | false |
|---------------|-------------------------------------------------------|
| Boolean | The result equals the input argument (no conversion). |
|---------------|-------------------------------------------------------|
| Number | The result is false if the argument is +0, −0, or NaN;|
| | otherwise the result is true. |
|---------------|-------------------------------------------------------|
| String | The result is false if the argument is the empty |
| | String (its length is zero); otherwise the result is |
| | true. |
|---------------|-------------------------------------------------------|
| Object | true |
+-----------------------------------------------------------------------+
Note: The last line object, which includes both objects and Arrays.
But in the later case, as per The Abstract Equality Comparison Algorithm,
If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
value of x will be converted to a number and that number will be checked against true.
Note:
In JavaScript, true is 1 and false is 0.
console.log(1 == true);
# true
console.log(0 == false);
# true
Several cases evaluate to false in the first form, such as empty string, 0, undefined, null.
If you want to be a bit more semantic about it, try the bang bang in front of the expression:
if(!!x){...}
this will convert the expression result to a truthy representing the same semantically. This is closer to an analogue to the expression you describe (x == true)
Also be aware that == is value comparions with type coercion, eg "3" == 3, whereas === asserts equal typing too.
So they are not the same, but often logically represent the same test, thanks to the semantics of the language and the !! you can use

Categories