Dot or bracket notation

Tell us what’s happening:

My doubt is regarding why is dot notation is giving error and how can I know what to use I mean dot or bracket notation for avoiding errors

Your code so far

function countOnline(usersObj) {
 // Only change code below this line
 let i=0;
for (let user in usersObj) {

if( === true){

return i;

 // Only change code above this line

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36.

Challenge: Iterate Through the Keys of an Object with a for…in Statement

Link to the challenge:

Hi @yashaswidasari!

Welcome to the forum!

Reading through this previous discussion might help.

Hi, it seems that within your for loop you are iterating through usersObj in which it is assigning the “current user” of the loop in the user variable. This is happening in this line:

for(let user in usersObj) {

Then inside this loop, you run into this issue:

if ( === true) { ... }

Unfortunately I do not know what your usersObj entails, but I assume it’s something like this:

const usersObj = {
  Alan: {
    age: 21,
    online: false
  Abbey: {
    age: 24,
    online: true

now, what you are doing with usersObj.user is looking inside this object for the name user when you use “dot notation”. “Bracket notation” will allow you to use a variable to index an object.

if you were to console.log or print out the user variable, you’d see that it would print out the names of the users. e.g.

for ( let userName in usersObj ) {
   console.log(userName); // Alan, Abbey

So, if you want to search usersObj for a key with the variable you’d do.

for ( let userName in usersObj ) {
 let userObj = usersObj[userName];
  console.log(userObj); // {age: 21, online: false}, {age: 24, online: true }

Reasons you’d use bracket notation over dot notation:

  • you don’t know the name of the property you want to access inside an object
    • e.g. the example above
  • you know you want to access one of a few properties based on certain conditions
    • e.g. you have a form and on submission you have a confirmation dialog, but you also have a feature where a user said “don’t show this again” (note there are better ways to write the following code example)
function onFormSubmit() {
  let submitFunctionName = 'confirmAndSubmit';
  if (window.dontShowConfirmations) {
    submitFunctionName = 'submit';

  // again, note: in industry people prefer methods more
  // readable than this
1 Like

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