Understanding code

Learning JS. Given a solution for twoSum in leetcode as follows:

var twoSum = function(nums, target) {
    let myObj = {}
    for (let i = 0; i < nums.length; i++) {
      let first = nums[i]
      let second = target - first
        if (myObj[second] !== undefined) {
            return [myObj[second], i]
        } else myObj[first] = i
     }
    }

I would like to understand what it means by myObj[second] and return [myObj[second], i]. thanks

For future reference, it will help if you provide a link to the source so we know what the function is supposed to do and the inputs that will be passed into it.

leetcode - Two Sum

myObj is an object and myObj[second] is attempting to access the property name stored in the variable second on the myObj object.

This returns a two element array, the first element is the value stored at myObj[second] and the second element is the current value of i.

hmmm. what is the property name stored in variable second? target - first returns a number…right?

link to source: Loading...

my inputs are, for example: console.log(twoSum([9,4,8,1], 12));
where the return should be: [1,2]

thanks.

Hi,

Link: Loading...

Inputs: console.log(twoSum([9,4,8,1], 12));

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

what is the property name stored in the variable “second”? “target - first” is equal to a number?

let first = nums[i]
let second = target - first

We know that nums is an array of numbers, so nums[i] will be a number, which means that first is a number. We also know that target is a number, so target - first will be a number.

got it. thanks.

quick question: could I have written myObj.second (to access properties of the object) instead of myObj[second]. One is dot notation and the other is with brackets.

No, not in this case, because second is a variable that holds the name of the property you want to access. Whenever you use a variable to access a property on an object you must use brackets. Now if the actual property name on the object was “second” then you could use dot notation.

Thanks for the info. Will do so in the future.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.