Attempting to grasp the concept of ternary condition logic in this specific scenario

Recently, I delved into a code kata involving an array of football scores such as:

["3:1", "2:2"]   (The total points here would be 4, 3 + 1)

After applying certain rules and summing up the points, I came across an interesting solution:

const points = g => g.reduce((a, [x, _, y]) => a + (x > y ? 3 : x == y), 0)

Just to clarify, the rules dictate that if the 1st value is greater than the 2nd, return 3 points, if they are equal, return 1 point, otherwise return 0. This mimics a traditional football match scoring system.

I'm curious about how the "x == y" part functions in this scenario. According to the rule, if "x == y", a single point should be returned. Can someone simplify this with an example?

Also, if someone could shed light on the "[x, _, y]" part, I would be grateful. I understand that it's supposed to represent the current item in the array, but since the current item is a string and not an array, I'm a bit confused about what's happening here.

Answer №1

The way JavaScript handles true and false values is crucial in understanding the outcome. You can test this in the console by entering the following:

let x = 1;
let y = 2;
2 + (x == y);

What will the result be in this case? Evaluating x == y gives us false, so the last line simplifies to:

2 + (false);

When resolving the addition, JavaScript turns false into a number, which in JavaScript equals 0. Therefore, the expression becomes:

2 + 0

Now, let's try another example:

let x = 1;
let y = 1;
2 + (x == y);

What outcome do we anticipate this time? With x == y evaluating to true, which is coerced to a 1, the calculation becomes:

2 + 1;

Answer №2

Breaking down the string

x represents the first character, _ is a variable that is not used, and y stands for the third character;

const [x, _, y] = "7:2";

console.log(x);
console.log(_);
console.log(y);

Answer №3

One interesting quirk in JavaScript is how type coercion can lead to surprising results.

For example, true can be coerced into 1 when used in arithmetic operations like this:

console.log('hi' == 'hi');  // true
console.log(0 + (true));  // 1
console.log(0 + ('hi' == 'hi'));  // 1

Answer №4

Check out this node session for a lesson. It demonstrates modern JS string-to-array destructuring and some boolean behaviors.

micha@linux-micha: ~
$ node
> [...arr] = "hello";
'hello'
> [...arr]
[ 'h', 'e', 'l', 'l', 'o' ]
> [x, dummy, y] = "3:2"
'3:2'
> x
'3'
> y
'2'
> dummy
':'
> typeof (x == y)
'boolean'
> typeof true
'boolean'
> typeof false
'boolean'
> 1 + true
2
> 1 + false
1
>

From this node session, observe how "3:2" is deconstructed into an array, resulting in x=3, y=2. Therefore, x==y evaluates to true. Within the function, there is a + operation that converts the boolean true value (x==y) to a numeric 1. This leads to a final output of 1.

Best regards, M.

Answer №5

Strings can be treated like arrays with indexes, allowing access to specific characters:

Therefore, it is possible to destructure strings.

console.log("3:1"[0]);
console.log("3:1"[1]);
console.log("3:1"[2]);
.as-console-wrapper { max-height: 100% !important; top: 0; }

In this example, the first, second, and third indexes are being accessed [x, _, y]

let [x, _, y] = "3:1";
console.log(x, _, y);

Coercion is demonstrated by a + (x == y), where true results in 1 and false results in 0.

console.log(1 + false);
console.log(1 + true);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

After receiving a data token from the server in one controller, how can I efficiently utilize that token in a different AngularJS controller?

In my adminSearchCtrl controller, I am receiving data from the server in the form of a token and want to pass that token to another controller named "adminViewCtrl". How can I achieve this? adminSearchCtrl.js $scope.getUserDetails = function(selectedUser ...

Transforming jQuery code to pure vanilla Javascript

For my project, I decided to convert my jQuery code into native JavaScript. The goal is to eliminate the dependency on jQuery and achieve the same functionality. The current setup involves two pages - page.html and side.html. The page.html document fetches ...

It appears that the JavaScript array is able to modify itself autonomously

Currently, I am working on a project using P5.js where I am saving values in an array and then creating a copy of that array to manipulate. However, I have encountered an issue where manipulating the second array also changes the original one, and I cannot ...

Listen for changes in the clientWidth of an element in Vue 3

Hey there, I'm currently working on a project where I need to track the clientWidth of a component when it gets resized. I'm trying to achieve this by using: const myEl = document.querySelector('#myID') and monitoring changes in myEl. ...

How to Stop Browser Tooltip from Displaying HTML Tags within "innerHtml" in Angular 6

In my Angular application, a template is using the following code snippet: ... <span [innerHtml]="textVar"></span> ... The textVar variable is created to allow for special styling on certain characters or strings. It's formatted using th ...

Issue with OnChange event in HTML and Adding Content with Jquery

I'm currently working on an app that includes a dynamic dropdown feature using jQuery and the append() method to display changing numbers dynamically. Everything seems to be functioning well in the first field of the form, but when I try to add more f ...

What could be causing my issue with the if-else condition not functioning properly?

Why does the code only work for adding and removing styles in Part (else), but not returning the class when clicked again? var navDropDown = document.querySelectorAll('.menu-item-has-children > a'); for (let i = 0; i < navDropDown.length; i ...

Tips for mocking a particular http resource (URL) solely in Angular

I'm part of a team with front-end and back-end developers. At times, the front-end team needs to make REST requests to an http address or REST-resource that hasn't been implemented yet. Within ngMockE2E, I've come across the $httpBackend se ...

Issue with dynamically adjusting flex box width using JavaScript

Currently, I am developing a user interface that heavily relies on flexbox. The layout consists of a content area and a sidebar that can be toggled by adding or removing a specific class. Whenever the sidebar is toggled, the content area needs to be manua ...

Looking for some help with tweaking this script - it's so close to working perfectly! The images are supposed to show up while

Hey everyone, I'm struggling with a script issue! I currently have a gallery of images where the opacity is set to 0 in my CSS. I want these images to become visible when scrolling down (on view). In this script, I have specified that they should app ...

The statement ""x=x || 4" will result in a `ReferenceError: x is not defined` because the

What is the reason behind receiving a ReferenceError: x is not defined error when using x = x || 4 or even x=(x||5), while var x = x || 4 operates as intended? ...

When JSON contains slashes, JSON.parse will trigger an error

I am struggling with a valid JSON generated using PHP like this: var json = <?php echo json_encode(['somearray']); ?>. Inside the array, there is an HTML string as shown below: $myArray = ['image' => '<img src="/img/f ...

Showcasing pictures with a prominent large image accompanied by two smaller ones on the right side

In my use of Material-ui-next, I am attempting to create images in a specific layout. ------ --------- | | | | 2 | | | | 1 |---| | | | | 3 | ------ --------- I have encountered some unusual issues. 1 - 3 appears below 1 ...

Exploring the process of incorporating a JavaScript library into an Angular project

I've encountered this issue before and know there are various workarounds available. I often search online for front-end design code to enhance the user experience of my projects, such as carousels, animations, and more. However, most of these project ...

What is the best way to retrieve the chosen option when clicking or changing using jQuery?

CSS <form name='category_filter' action='/jobseek/search_jobs/' method='get'> <select id="id_category" class="" name="category"> <option value="" selected="selected">All</option> <option v ...

I'm encountering an issue where the data in my personalDeatail model's add value is not updating automatically. Can someone please help me

I've been struggling to automatically update the data in model personalDetail.add value when adding two column data. The added data appears correctly in the input box, but it's not updating in personalDetail.add. What am I missing here? Help need ...

Is it possible to update my services list based on which checkboxes I choose to uncheck at the top?

i am currently tackling a small project, and I have limited experience with javascript and json. Can someone assist me in resolving the final step? I am on the verge of completing it, but encountering some issues. My goal is to filter the results based on ...

How to use jQuery to iterate over changing elements and retrieve their data values

Exploring the potential of a collapsible panel to meet my requirements $(".sport").on("click", function() { var thisId = $(this).attr("id"); var thisChildren = $(this) + ".sportlist"; $(thisChildren).each(function(index) { }); }); <link ...

I am struggling to showcase the values of character names stored within an array

I am currently developing a Library Express App and utilizing fake data to easily showcase the values on the screen. const PopularBooks = [ { id: 1, title: "Harry Potter", characters: [ { id: 1, name: "Har ...

Dealing with non-string values (such as Date, Double, Boolean) when creating JSON through iterative mapping with Map and Object Array in Scala

How can I handle non-string values (Date, Double, Boolean) when building JSON in Scala by looping with Map and Object Array? In the following example, I always end up with non-string values as strings in the Values Array. import play.api.libs.json._ impor ...