Im brand new to javascript. I simply have an exercise where i need the array numbers to add each index to the next one.
The result should be:
var result = [4,8,15,21,11];
I tried something like this. It works on the first 4 indexes, however gives NaN on last since it doesnt have a next number to add to.
var numbers = [1, 3, 5, 10, 11];
var result = numbers.map((x, index) => x + numbers[index + 1])
console.log(result)
Is there any smarter way to do this and how do i get index 4 to stay as 11? And please explain as im trying to learn.
That's a perfectly valid way to do it. You can handle the last index by taking advantage of the fact that numbers[index] will be undefined (not an error) if index is beyond the end of the array, and undefined is a falsy value, so you can use || 0 to use 0 instead of undefined if it's there:
var result = numbers.map((x, index) => x + (numbers[index+1] || 0));
Live Example:
var numbers = [1, 3, 5, 10, 11];
var result = numbers.map((x, index) => x + (numbers[index + 1] || 0));
console.log(result);
|| is the logical OR operator, but it's a bit special in JavaScript: It evaluates its left-hand operand and, if that value is truthy¹, takes that value as its result; if the left-hand is falsy, the operator evalutes the right-hand operand and takes that value as its result.
In ES2020+ you can use the new nullish coalescing operator (??) instead of ||:
var result = numbers.map((x, index) => x + (numbers[index+1] ?? 0));
That will only use the 0 if numbers[index] is null or undefined, rather than if it's any falsy value.
¹ "truthy" and "falsy" - A truthy value is a value that evaluates to true when used as a condition (for instance, if (x) or x || y); a falsy value is a value that evalutes to false. The falsy values are 0, "", NaN, null, undefined, and of course, false. All other values are truthy. (Except there's a special case on browsers: document.all is falsy for legacy reasons.)
Related
Can anyone explain the meaning of the assign operator? What does it mean?
It came out as true but I'm unclear on how we reached to there.
Thanks!
var x = 0 !=1;
An assignment operator assigns a value to its left operand based on the value of its right operand. In this case true will be assigned to the variable x as 1!=0 (1 not equal-to 0) is true.
Order of operations (var x = (0 != 1))
Imagine you computed just 0 != 1. This is evidently a true statement, so this would evaluate to true. If you set x to the evaluation of 0 != 1, then you receive var x = true.
Can someone please explain JavaScript Truthy and Falsy, using the below sample data. I have read other threads but still confused.
var a = 0;
var a = 10 == 5;
var a = 1;
var a = -1;
From my understanding, I believe that var a = 1; is the only truthy and the rest are falsy - is this correct?
From my understanding, I believe that var a = 1; is the only truthy and the rest are falsy’s - is this correct?
No.
var a = 0;
Number zero is falsy. However, note that the string zero "0" is truthy.
var a = 10 == 5;
This is same as var a = (10 == 5);, so this is falsy.
var a = 1;
var a = -1;
Any non-zero number including negative numbers is truthy.
Quoting from MDN
In JavaScript, a truthy value is a value that translates to true when evaluated in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for false, 0, "", null, undefined, and NaN).
List of falsy values in JavaScript:From MDN
false
null
undefined
0
NaN
'', "", ``(Empty template string)
document.all
0n: BigInt
-0
There's a simple way to check, which you can use now and forever:
function truthyOrFalsy(a) {
return a ? "truthy" : "falsy";
}
To wit:
> truthyOrFalsy(0)
"falsy"
> truthyOrFalsy(10 == 5)
"falsy"
> truthyOrFalsy(1)
"truthy"
> truthyOrFalsy(-1)
"truthy"
Also see a list of all falsey values in JavaScript.
Truthy -> Value that resolve to true in boolean context
Falsy -> Value that resolve to false in boolean context
For better understanding, `falsy` values are given below.
false
0
empty string
null
undefined
NaN
FALSY
false
0 (zero)
"", '', `` (empty strings)
null
undefined
NaN (not a number)
note : Empty array ([]) is not falsy
TRUTHY
Everything that is not FALSY
The below answer might help someone.
As well as a type, each value also has an inherent Boolean value, generally known as either truthy or falsy. Some of the rules are a little bizarre, so understanding the concepts and effect on comparison helps when debugging JavaScript applications.
The following values are always falsy:
false
0 (zero)
-0 (minus zero)
0n (BigInt zero)
'', "", `` (empty string)
null
undefined
NaN
Everything else is truthy. That includes:
'0' (a string containing a single zero)
'false' (a string containing the text “false”)
[] (an empty array)
{} (an empty object)
function(){} (an “empty” function)
A single value can therefore be used within conditions. For example:
if (value) { // value is truthy } else { // value is falsy // it could be false, 0, '', null, undefined or NaN }
one more check version:
function truthyOrFalsy(a) {
return (a && "truthy") || "falsy";
}
In short there are only 6 types of falsy values:
You can use this snippet to test them:
function isTruthy(val){
if(val){
console.log(val + ' is Truthy');
}else{
console.log(val + ' is falsy');
}
}
// all below are truthy
isTruthy (true)
isTruthy ({})
isTruthy ([])
isTruthy (42)
isTruthy ("0")
isTruthy ("false")
isTruthy (new Date())
isTruthy (-42)
isTruthy (12n)
isTruthy (3.14)
isTruthy (-3.14)
isTruthy (Infinity)
isTruthy (-Infinity)
//all below are falsy
isTruthy(0);
isTruthy("");
isTruthy(false);
isTruthy(NaN);
isTruthy(null);
isTruthy(undefined);
Refer this site for details: https://developer.mozilla.org/en-US/docs/Glossary/Falsy
Easy way to check Falsy Value and True value
function truthyOrFalsy(val){
if(val){
console.log (`${val} is truthy`);
} else{
console.log (`${val} is falsy`);
}
}
Check all FALSY value:
truthyOrFalsy(false); //Output: false is falsy
truthyOrFalsy(null); //Output: null is falsy
truthyOrFalsy(0); //Output: 0 is falsy
truthyOrFalsy(''); //Output: is falsy [blank refers to '']
truthyOrFalsy(NaN); //Output: NaN is falsy
truthyOrFalsy(undefined); //Output: undefined is falsy
Please note that undefined is not explicitly used to set as value.
Some common scenarios will create undefined:
Parameter defined in function but not passed argument in callback function.
If nothing returns in function
If accessing to an object property/method which is not defined
If accessing to an array element which is not defined
function add(num1, num2){
console.log(num1, num2);
}
const result = add(44);
console.log(result);
//Output: 44 undefined
// undefined
const car = {color:"Blue", price: 200000};
console.log(car.category);
//Output: undefined
arrColors = ["Blue", "Sky", "Purple"];
console.log(arrColors[5]);
//Output: undefined
Check all TRUTHY values
All values are truthy unless they are defined as falsy.
Although ' ', '0', -1, [] could be enlisted to be checked.
truthyOrFalsy(' '); //Output: is truty [blank refers to space inside
// quote ]
truthyOrFalsy('0'); //Output: 0 is truty
truthyOrFalsy([]); //Output: is truty [blank refers to an empty array]
truthyOrFalsy(-1); //Output: -1 is truty
Another way to evaluate whether something is truthy or falsy that I like to use is
function truthyOrFalsy(a) {
return !!a;
}
The following code uses the reduce method. It outputs the number of times an element appears in the array. If element appears once then it only outputs 1, otherwise if it is a repeated item then it it is added..
let a = ["a", "b", "c", "a", "b"]
const t = a.reduce((aa, ll) => {
const count = aa[ll];
count
?
aa[ll] = count + 1 :
aa[ll] = 1
return aa
}, {})
console.log(JSON.stringify(t))
// output
// { "a":2, "b":2, "c":1 }
Question is regarding the condition in the ternary operation, specifically the count variable. How is the count variable able to resolve true or false.
The concept is called "Truthy" and "Falsy" respectively. Ie anything that is different from false, 0, -0, 0n, NaN, null, undefined and "" (empty string) can be evaluated to true in Javascript
So your assign var counter = aa[ll] to be the value of the key ll in object aa. That's either a number or undefined. If it's a number !== 0 it's a truthy, if it's 0 or undefined it's falsy. Thus it can be used in a ternary operatator. Depending on the value of counter either the value of the first or the second assignment will be returned (but ignored). The return value of an assignment is always the value of the right hand side ...
While you can use also assignments in the expressions of a ternary operator, I personally wouldn't use it that way but write this assignment as follows
const t = a.reduce((aa, ll) => {
aa[ll] = (aa[ll] || 0) + 1;
return aa
}, {})
(aa[ll] || 0) will return the value of aa[ll] if it's a truthy or 0 otherwise. Thus, in your case, the result of this expression will always be a number >= 0. Then you increase the result by 1 (for the currenct occurence of ll) and assign it back to aa[ll]. This is much shorter than your original code and IMHO much more readable
Heres the answer I found.
"A javascript object consists of key-value pairs where keys are unique. If you try to add a duplicate key with a different value, then the older value for that key is overwritten by the new value."
basically the count variable was checking to see if the new property already exists.
I wonder, are these absolutely the same:
var a = something1.something2 === undefined ? 1 : something1.something2;
var b = something1.something2 || 1;
No. In the first one, something1.something2 has to be undefined in order to get the value 1. In the second one it merely has to be falsy. There are lots of falsy values: 0, "", NaN, null, undefined, and of course, false.
No they are not.
If you take the value 0 for something1.something2, then in the first case the return value is 0.
The second case returns 1, because of the falsy value of 0.
Closure(Script) implementation in JavaScript called "wisp" has this snippet:
(get [1 2 3] 1) ; => ([1, 2, 3] || 0)[0]
which means that the wisp code compiles to this in JavaScript:
([1, 2, 3] || 0)[0]
But why is || 0 part there?
My guess is that instead of writing a literal array, you can send it a variable:
(get x 1) ;
So the || 0 is used in case x is null or undefined.
In JavaScript, || does not return a boolean, it returns the 1st value if it's "truthy" and the 2nd if the 1st is "falsy".
0[0] returns undefined just like [][0] does. 0 is one less character than [], so that's probably why they did || 0 instead of || [].
Normally it would be used to specify a default value if the first part is null/undefined/false.
For example, consider the following code:
var a = 1;
var b;
var x = a || 0;//if a is true use a, otherwise use 0
var y = b || 0;//if b is true use b, otherwise use 0
The value of x will be 1, because 1 is a truthy value and therefore becomes the value that is used. whereas y will be 0 because the value of b is undefined (a falsey value) so the 0 is used instead.
In your example however it is pointless, as [1, 2, 3] will always be true. But if you was using a variable then is would be possible for the variable to not be assigned, so the default value would then apply.
Here is an example that shows how different types would apply
Here is more information on Truthy and Falsey vaues
I don't believe that the || 0 does anything. The || operator checks for a null, undefined etc, and if found will return the right hand side of the expression.
In this example [1, 2, 3] is never null so 0 will never be returned.