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.
Related
We know about post-increment and pre-increment in programming languages. As far as I know, post-increment means to increment the value for the next statement. So, something++ is the equivalent to something = something + 1, isn’t it?
But why do something = something + 1 and something++ produce a different output when something is a string?
let something = "5";
let anything = 5;
something = something + 1;
console.log(something); // "51"
anything = anything + 1;
console.log(anything); // 6
let something = "5";
let anything = 5;
something++;
console.log(something); // 6
anything++;
console.log(anything); // 6
I know about automatic type-casting, but why is something + 1 coerced into a string, but something++ into a number?
If you read the specification for the ++ operator, you’ll see that step 2 forces its operand to be a number, whereas + doesn’t.
12.4.4 Postfix Increment Operator
12.4.4.1 Runtime Semantics: Evaluation
UpdateExpression : LeftHandSideExpression ++
Let lhs be the result of evaluating LeftHandSideExpression.
Let oldValue be ? ToNumber(? GetValue(lhs)).
Let newValue be the result of adding the value 1 to oldValue, using the same rules as for the + operator (see 12.8.5).
Perform ? PutValue(lhs, newValue).
Return oldValue.
These are two different operators
++ is post increment it implicitly tries to coerce operands to number and then performs increment ++ Ref
let increment = (val) =>{
return val++
}
console.log(increment('5'))
console.log(increment(''))
console.log(increment([]))
console.log(increment({}))
console.log(increment(undefined))
whereas the other one is addition when used for numeric value but works as concatenation for string + Ref
let increment = (val) => {
return val + 1
}
console.log(increment('5'))
console.log(increment(''))
console.log(increment([]))
console.log(increment({}))
console.log(increment(undefined))
Let's look at the examples below:
Q1: Why is the output 0 here? What does it mean?
var a = 7;
console.log(a.constructor()); // prints 0 (Why?)
Q2: When typeof a and typeof 7 both are number, why a.constructor() runs whereas 7.constructor() doesn't?
var a = 7;
var bool = typeof a === typeof 7;
console.log(a.constructor()); // 0
console.log((++a).constructor()); // 0
console.log(7.constructor()); // SyntaxError: Invalid or unexpected token
console.log(++a.constructor()); // ReferenceError: Invalid left-hand side expression in prefix operation
Q1: Why is the output 0 here? What does it mean?
a.constructor is Number and you are calling it with first argument undefined. Because Number() returns undefined so x.constructor() returns undefined. If no argument is passed to Number() it returns 0
var a = 5;
console.log(a.constructor === Number)
console.log(Number())
When typeof a and typeof 7 both are number, why a.constructor() runs whereas 7.constructor() doesn't?
Actually 7. is itself a number. Here . doesnot work as Dot Notation but as decimal point because the digits after decimal point are optional.
Solution:
There can be different ways to directly access the method of number.
console.log(5..constructor)
console.log((5).constructor)
console.log(5 .constructor)
Q1: Because js number is object and has method constructor (which returns 0 when no parameter is provided)
Q2: Because first dot is interpret by js as decimal dot, but try
console.log( 7..constructor() );
Q1: Why is the output 0 here? What does it mean?
The constructor method is there to determine the type of the variable (Check the example)
var a = 7;
console.log(a.constructor == Number);
var b = new Object;
console.log(b.constructor == Number);
console.log(b.constructor == Object);
Q2: When typeof a and typeof 7 both are number, why a.constructor() runs whereas 7.constructor() doesn't?
Because the point after 7 is treated like a decimal and therefore it gives an error because constructor() is not a number. The code below would fix this (even tho it makes no sense):
console.log((7).constructor())
I have a very simple arithmetic operator but am at my wits end why it doesn't return 2. The code below returns 1. I thought that x++ equates to x = x + 1;
CODE
var x = 1;
document.write(x++);
However if I run the code as follows, it returns 2 as expected
CODE
var x = 1;
document.write(++x);
What am I doing wrong?
PostIncrement(variable++) & PostDecrement(variable--)
When you use the ++ or -- operator after the variable, the variable's value is not incremented/decremented until after the expression is evaluated and the original value is returned. For example x++ translates to something similar to the following:
document.write(x);
x += 1;
PreIncrement(++variable) & PreDecrement(--variable)
When you use the ++ or -- operator prior to the variable, the variable's value is incremented/decremented before the expression is evaluated and the new value is returned. For example ++x translates to something similar to the following:
x += 1;
document.write(x);
The postincrement and preincrement operators are available in C, C++, C#, Java, javascript, php, and I am sure there are others languages. According to why-doesnt-ruby-support-i-or-i-increment-decrement-operators, Ruby does not have these operators.
I think of x++ and ++x (informally) as this:
x++:
function post_increment(x) {
return x; // Pretend this return statement doesn't exit the function
x = x + 1;
}
++x:
function pre_increment(x) {
x = x + 1;
return x;
}
The two operations do the same thing, but they return different values:
var x = 1;
var y = 1;
x++; // This returned 1
++y; // This returned 2
console.log(x == y); // true because both were incremented in the end
If you take a look at the javascript specification pages 70 and 71 you can see how it should be implemented:
Prefix:
Let expr be the result of evaluating UnaryExpression.
Throw a SyntaxError exception if the following conditions are all true:72 © Ecma International 2011
Type(expr) is Reference is true
IsStrictReference(expr) is true
Type(GetBase(expr)) is Environment Record
GetReferencedName(expr) is either "eval" or "arguments"
Let oldValue be ToNumber(GetValue(expr)).
Let newValue be the result of adding the value 1 to oldValue, using the same rules as for the + operator (see
11.6.3).
Call PutValue(expr, newValue).
Return newValue.
Or more simply:
Increment value
Return value
Postfix:
Let lhs be the result of evaluating LeftHandSideExpression.
Throw a SyntaxError exception if the following conditions are all true:
Type(lhs) is Reference is true
IsStrictReference(lhs) is true
Type(GetBase(lhs)) is Environment Record
GetReferencedName(lhs) is either "eval" or "arguments"
Let oldValue be ToNumber(GetValue(lhs)).
Let newValue be the result of adding the value 1 to oldValue, using the same rules as for the + operator (see
11.6.3).
Call PutValue(lhs, newValue).
Return oldValue.
Or more simply:
Assign value to temp
Increment value
Return temp
This question already has answers here:
Why doesn't the shorthand arithmetic operator ++ after the variable name return 2 in the following statement?
(3 answers)
Closed 6 years ago.
Please can someone explain to me why my addOne function doesn't work with the increment operator (++). Please see my code below.
// addOne Function
function addOne(num){
return num + 1
}
log(addOne(6)) => 7
// same function with ++ operator
function addOne(num){
return num++
}
log(addOne(6)) => 6
// Question - why am I getting 6 instead of 7 when I use ++ operator?
There are two increment operators: prefix and postfix.
The postfix operator increments the variable after it is evaluated. For example, the following code produces 11, because it adds 5 and 6:
var a = 5;
(a++) + (a++)
The prefix operator increments the variable before it is evaluated. Sounds like that is what you want. The following code produces 13, because it adds 6 and 7:
var a = 5;
(++a) + (++a)
So your code should be:
function addOne(num) {
return ++num;
}
console.log(addOne(6));
That is not the correct use of ++, but also a lot of people would not recommend using ++ at all. ++ mutates the variable and returns its previous value. Try the example below.
var two = 2;
var three = two += 1;
alert(two + ' ' + three);
two = 2;
three = two++;
alert(two + ' ' + three);
two = 2;
three = two + 1;
alert(two + ' ' + three);
num+1 increments the number before the current expression is evaluted so log will be the number after increment, but num++ increments the number after the expression is evaluated, so log will log the num before increment then increment it.
if you like to do the same functionality as num+1 you may use ++num and it will do the same.
They both increment the number. ++i is equivalent to i = i + 1.
i++ and ++i are very similar but not exactly the same. Both increment
the number, but ++i increments the number before the current
expression is evaluted, whereas i++ increments the number after the
expression is evaluated.
See this question
I understand that when a variable is declared it is given the value "undefined", but I don't understand why the following code doesn't work (returns NaN):
function sum() {
// return the sum of all arguments given.
var answer;
for (var i = 0; i<arguments.length; i++){
answer += (arguments[i]);
}
console.log(answer);
}
sum(4,5,3,2);
In order to get the correct answer (14), I had to initialize the answer variable:
var answer = 0;
Simply put: you cannot add to "undefined". The answer is... undefined, or not a number. You can, however, add to zero, so of course you have to initialize the variable to 0.
In essence, you're asking why undefined + 5 + 4 + 3 + 2 is NaN (not a number). The answer is that, when you treat undefined as a number, it is implicitly converted to NaN. Any operation on NaN will, in turn, result in NaN.
answer += (arguments[i]);
equals
answer = answer + (arguments[i])
answer being initially undefined, you actually have
answer = undefined + (arguments[i])
which is a NaN:
alert(undefined + 42);
Because you are trying to add a number to an undefined variable this is not possible because you are trying to add a number to answer which isn't a number until you initialize it.
Leaving answer uninitialized is equivalent to
var answer = undefined;
And since (undefined + any number) is also NaN (not a number) each loop does nothing but keep reassigning answer to NaN
console.log(undefined + 0); => NaN
console.log(NaN + 1); => NaN
console.log(NaN + 2); => NaN
Try undefined + 1 (a variable not initialized resolves to undefined) in the console: its result is NaN (Not a Number), so any next iteration NaN + some number will be NaN.
Alternatively you can use Array.reduce (see MDN for more on that) to calculate the sum:
function sum() {
// return the sum of all arguments given.
return ([].slice.call(arguments)).reduce(function (a, b) {
return a + b;
});
}
document.querySelector('#result')
.innerHTML = '<code>sum(1,4,3,5,6)</code> => ' + sum(1, 4, 3, 5, 6);
<div id="result"></div>