JS object and number addition [duplicate] - javascript

This question already has answers here:
Why does `{} + []` return a different result from `a = {} + []` in Javascript?
(2 answers)
Why {} != ( {} ) in JavaScript?
(2 answers)
Closed 4 years ago.
{} + 5 === 5
5 + {} === '5[object Object]'
How is the first expression {} + 5 === 5 calculated?
The second expression 5 + {} === '5[object Object]' is expected result.
===== Edit ====
({}) + 5 === '[object Object]5'
Which might be to say: {} in first expression was ignored as the question comment says.

The {} at the beginning of a line is considered a code block rather than an object literal. Thus {} + 5 is not considered a binary addition between two values and evaluates to +5, unary + operator applied to 5.
When {} is placed inside round brackets it turns into object literal and the entire expression evaluates to '[object Object]5'
More details on this gotcha can be found here

In the following snippet, both expressions are converted to strings, so you get the following results, which is expected:
[object Object]5
5[object Object]
The reason this is happening is because + can't be addition between numbers since {} can't be cast to a number. Instead + is considered string concatenation here and both operands get converted to strings.
console.log({} + 5 === '[object Object]5')
console.log(5 + {} === '5[object Object]')

Related

Why is the output of `function test(){} + 1;` is 1?

Why is the output of the following code is 1
function test(){} + 1; // output: 1
Because of automatic semicolon insertion, that code is actually processed as:
function test(){}; + 1;
That's the unary plus operator, not the addition operator.
function test() or {} here is not an Object, its en empty statement and JS Cannot convert object to primitive value and find the safe route and convert this statement value to false.
{} + 1 = 1 because (false + 1) = always 1.

JavaScript variable: var a =(3,4,7); [duplicate]

This question already has answers here:
What does the comma operator do in JavaScript?
(5 answers)
Closed 4 years ago.
var a =(3,4,7);
console.log(a); // Output is 7
Can you please explain how we are getting output 7?
It's called comma operator. By wrapping the right hand expression in parentheses we create a group and it is evaluated each of its operands and returns the last value.
From MDN
The comma operator evaluates each of its operands (from left to right)
and returns the value of the last operand.
The comma operator is useful when you want to write a minifier and need to shrink the code.
For instance,
print = () => console.log('add')
add_proc = (a,b) => a + b
function add(a, b){
if(a && b){
print();
return add_proc(a,b)
}
else
{
return 0
}
}
console.log(add(1,2));
could be minified using comma operator as below:
print = () => console.log('add')
add_proc = (a,b) => a + b
add = (a, b)=> a && b ?(print(),add_proc(a, b)):0
console.log(add(1,2));
The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.
Here , Seprates each Digits Ans As it is a Variable So it stores 3 then overlapped by 4 and finally 7
So final output is 7

Confusing results with typeof and isNaN with (1 + undefined) operation [duplicate]

This question already has answers here:
Why does typeof NaN return 'number'?
(21 answers)
Closed 4 years ago.
Consider the following operation:
typeof (1 + undefined) => "number"
and now this operation:
isNaN(1 + undefined) => true
typeof states that the result of (1+undefined) should be a number.
While, the operation of if (1+undefined) is not a number is true.
How is this possible?
NOTE: I tested this in console of google chrome if that matters.
The answer is simple: NaN is a number.
The term "not a number" doesn't mean "not a member of the type number in JavaScript". It's a term from the relevant floating-point specification, in which a set of bit patterns is collectively used to designate values that are "not numbers"; that is, the bit patterns are not valid.
It's somewhat unfortunate that JavaScript was designed such that certain operations that have numerically meaningless results yield NaN, since the point of NaN in the spec is to designate values to be avoided. It's too late to revisit that decision however.
The global isNaN() function always attempts to convert its argument to number before performing the test. Thus, it's often used to check if a string value contains digits that can be interpreted as a valid number.
Because typeof (1 + undefined) is typeof NaN, and
typeof NaN === "number" //true
Since (1 + undefined) result in NaN you get that behaviour. Check the examples below:
var value = 1 + undefined;
console.log('value for (1 + undefined) is ' + value);
var result1 = typeof (1 + undefined);
console.log('typeof (1 + undefined) is ' + result1);
//this result2
var result2 = isNaN(1 + undefined);
console.log('result of isNaN(1 + undefined) is ' + result2);
//is same as
result2 = isNaN(NaN); //as 1 + undefined is NaN
console.log('result of isNaN(NaN) is ' + result2);

Why is Infinity a number? [duplicate]

This question already has answers here:
Infinity is some number in javascript?
(3 answers)
Closed 6 years ago.
In JavaScript, isNaN(Infinity) returns false, as if Infinity were a number; but several arithmetic operations on Infinity behave as if it were the mathematical infinity, which is not a number:
So, why doesn't isNaN(Infinity) return true? Is it because its value defaults to a Number object?
Infinity is not NaN because you are able to use it in mathematical expressions. Obviously 1 + NaN would never work, but 1 + Infinity returns Infinity (See here). Many of the examples that you have in your link are mathematically indeterminate, which is why they return as Nan. For example, Infinity * 0 is indeterminate (See here).
Hope this helps.
The reason isNaN(Infinity) returns false has nothing to do with mathematical technicalities, it's simply because its implementation is equal to this:
function isNaN(object) {
var coerced = +object;
return coerced !== coerced;
}
In other words, it coerces the input to a Number. If the coerced value is determined to be NaN (by checking if it is not strictly equal to itself), then it returns true. Otherwise it returns false.
[Infinity, null, undefined, true, new Date(), {}, [], [1], [1,2,3], 'blah', '4'].forEach(function (object) {
console.log('object: ' + (typeof object !== 'number' ? JSON.stringify(object) : object));
console.log('coerced: ' + (+object));
console.log('isNaN: ' + isNaN(object));
console.log('==================');
});

How to have a statement identify an undefined variable? [duplicate]

This question already has answers here:
How to check a not-defined variable in JavaScript
(15 answers)
Detecting an undefined object property
(50 answers)
Closed 8 years ago.
Let's say you have the following function:
var variable;
function(variable);
function function(variable) {
alert ("variable equals " + variable);
if (variable != 'undefined') {
~~~code1~~~
} else {
~~~code2~~~
}
}
The alert outputs:
variable equals undefined
However, ~~~code2~~~ is never executed. I'm guessing that my syntax is incorrect. If I haven't defined the variable, how do I get the function function to execute ~~~code2~~~?
Extra Information
When the variable variable is hardcoded, as in the following code:
var variable;
function(variable)
function function(variable) {
variable = 2;
alert ("variable equals " + variable);
if (exponent == 2) {
~~~code1~~~
} else {
~~~code2~~~
}
}
~~~code1~~~ is executed.
> exponent != 'undefined'
You need to understand the Abstract Equality Comparison Algorithm. The above attempts to compare the value of exponent with the string "undefined". Since exponent is defined but has not been assigned a value, it will return the value undefined which is not equal to the string "undefined" (according to the algorithm above).
So you can compare its value to the undefined value:
exponent != undefined
or you can compare the type of the value with an appropriate string value using the typeof operator (since it always returns a string):
if (typeof exponent != 'undefined')
Whether you use the strict or abstract versions above (!== or != respectively) doesn't make any difference in this case.

Categories

Resources