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.
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.
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.
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.