setting a variable equal to an array element

While I was working on a problem, I encountered a situation that I was able to resolve, but I must admit, I don't fully comprehend how it works.

var array = [3, 6, 2, 56, 32, 5, 89, 32];
var largest = 0;
//Snippet of my code
for (var i = 0; i < array.length; i++) {
    if (array[i] > largest) {
        largest = array[i];
    }
}

console.log(largest);

I'm unsure about how my array assigns a value to my variable within the if statement.

Could you explain why this alternative version doesn't produce the desired result?

array[i] = largest;

As someone who is relatively new to programming, I believe grasping fundamental concepts, no matter how small, is crucial for aspiring programmers to develop their skills effectively.

Answer №1

if(array[i] > largest) {
           largest = array[i];
        }

array[i] is 3 and largest is 0 then when the condition is met

largest = array[i];

the value is assigned from right to left now the largest value becomes 3.

in the next cycle, if array[i] is 6, then 6 > 3 is true, so largest is updated to 6.

This process continues to find the largest number in the array.

Answer №2

It seems like there may be some confusion between programming assignment statements and mathematical equality statements.

Understanding Assignment and Equality

When you write largest = array[i] in your code, you are simply assigning the value of the element at position i in the array to the variable 'largest'. This does not change any values in the array itself.

On the other hand, if you were to write array[i] = largest, you would be attempting to update the value at position i in the array with the current value of the variable 'largest'.

Answer №3

This piece of code aims to find the maximum value in a specified array of values.

For example:

array[i] = largest;

This line of code would change the original input, which is not the desired outcome. The goal is to identify the highest value in the array without altering the input array itself.

Therefore, the correct approach is:

largest = array[i]

Because this method accurately locates the largest value without changing the original input.

Answer №4

When you set a value to a variable, remember that the variable should always be on the left side of the equals sign.

For example, this code assigns the value of array[i] to the variable largest:

largest = array[i];

However, if you reverse the order like this:

array[i] = largest;

You'll actually be putting the value of largest into the element array[i], resulting in unexpected behavior like zeros filling up your array.

Answer №5

Although this thread is old, I faced this issue today and wanted to share knowledge from Kyle Simpson to help other developers.

You don't know JS

Operator assignment has its own unique way of functioning. It evaluates the expression on the right side of "=" before assigning it to the left side. Understanding this process is crucial.

For example:

var array = [3, 6, 2, 56, 32, 5, 89, 32];
var largest = 0;
//My code
for (var i = 0; i < array.length; i++) {
    if (array[i] > largest) {
        largest = array[i];
    }
}

console.log(largest);

Here, largest = array[i];

JavaScript evaluates the expression on the right and assigns it to the left

Enjoy exploring the book and experimenting with code.

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

CSS - using numbers to create dynamic background images

I am looking to create a design where the background images in CSS display increasing numbers per article, like this example: This idea is similar to another post on Stack Overflow discussing using text as background images for CSS. You can find it here: ...

Is Javascript Functioning Properly?

Similar Question: How do I determine if JavaScript is turned off? Can we identify whether javascript has been disabled and then redirect to a different page? I am currently working on a project using JSPs, where I have integrated various advanced java ...

AngularJS flexible route parameter

My AngularJS application has routes that can be either: www.website.com/blog/xyz www.website.com/blog/xyz/title/other-params In the second URL, the title parameter is used for readability purposes only and is not mandatory in the URL. Therefore, I have i ...

The modal window pops up immediately upon the first click

Experience a dynamic modal element that springs to life with just the click of a button or an image. The magic lies in the combination of HTML, CSS, and jQuery code: <div id="modal-1" class="modal"> <div class="button modal-button" data-butto ...

Problem with Ionic App crashing

Currently, I am developing an Ionic app that relies on local storage for offline data storage. The app consists of approximately 30 different templates and can accommodate any number of users. Local storage is primarily used to store three key pieces of i ...

Having trouble with Node.js child_process.exec when the command doesn't return any output?

Recently encountered an issue while using child_process.exec in nodejs. The problem occurs when the command returns nothing. Here is what I did: const {exec} = require('child_process'); const cmd = `ps -ef | grep -v grep | grep abc123.py`; exec ...

Tips for making nested sliding divs within a parent sliding div

Is it possible to slide a float type div inside another div like this example, but with a white box containing "apple" text sliding inside the black div it's in? I have attempted to recreate the effect using this example. Here is my current JavaScript ...

What could be the reason for my onChange event not functioning properly?

The issue I'm experiencing involves my onchange event not properly copying the text from the current span to the hidden field. Any ideas on why this might be happening? Check out my code at this link. ...

The issue with AngularJS ng-show and $timeout functionality not functioning as expected

As a newcomer to AngularJS, I recently started an individual project utilizing ng-show and if else statements with $timeout. Despite my efforts, I have been unable to make the answers timeout after being displayed for a few seconds. I've tried various ...

Retrieving a channel using its unique ID and then sending a message directly into it

I am attempting to retrieve a channel by its ID and then send a message to it, but I keep encountering an error when running the code. ERROR: Error sending message to welcome channel.: TypeError: Cannot read properties of undefined (reading 'send&apos ...

Add a click function to an element in a grid when it is databound

In my TypeCtrl ES6 class angular controller, I am using a kendo datagrid directive with a template for grid config options. Within the grid template, I need to call a method from the TypeCtrl class when a span within the row is clicked. However, the functi ...

Passing a variable from one Tkinter class to another Tkinter class within the same window - not involving a toplevel frame

How can I pass the value of a variable from one class to another in tkinter with python, especially when they are sharing the same frame instead of being separate windows? For instance, if I have a login window and want to send the username and account pr ...

The functionality to refresh an input field upon clicking a button is not functioning as expected

I am currently developing a small MVC.NET web application with user input functionality. The goal is to calculate and display the results in two input fields upon button click. However, I am facing an issue where the input fields remain empty after the but ...

What is the process for connecting personalized toggle controls to a checkbox input field?

I have created a custom slide toggle control to enhance the functionality of my checkboxes in the app. You can check out the controls by following this link: http://codepen.io/spstratis/pen/fJvoH Currently, I am looking for a way to connect these switche ...

How does React-router handle component reloading when there is a change in the state of the parent component

Within my React application, I've integrated a ResponsiveDrawer component sourced from material-ui's demo. This component essentially displays a drawer containing a list of menu items, a title bar, and a content frame. The state of the component ...

SyntaxError: End of input caught unexpectedly (NodeJS TCP server)

My simple tcp server has the capability to send and receive json data. Here is a snippet of my code: // Handling incoming messages from clients. socket.on('data', function (data) { var obj = JSON.parse(data); if(obj.type == "regis ...

Add the "multiple" attribute to ui-select only if certain conditions are met

I am attempting to dynamically add the multiple attribute to a ui-select directive based on the value of a specific property by using the ng-attr- directive. Unfortunately, this method is not functioning as expected in my case. To better illustrate the iss ...

How can I refresh the node server during runtime?

In my Express server, I am currently working on defining an endpoint that triggers a restart of the server automatically during runtime. Here is a snippet showcasing how this could be implemented: var express = require('express') var app = expre ...

Transforming a character array into an array of unsigned 16-bit integers in C/C++

Here is my code snippet that converts and stores data from a string (array of characters) named str into an array of 16-bit integers called arr16bit: While the code works, I believe there might be a more efficient and cleaner way to implement this logic, ...

Despite being logged, the current value of firebase.auth().currentUser in Firebase is null

I have coded a query in my service.TS file that displays the "state" of items based on the UID of the logged-in user: getLists(): FirebaseListObservable<any> { firebase.auth().onAuthStateChanged(function(user) { if (user) {console.log("blah", fir ...