1
function me(a, b) {
    function he(c, d) {
       if(!a[c]) { 
    } 
  }
}  

Please someone explain 'if(!a[c])' for me. why this square bracket is used here in [c], it is not an array obviously. What does if(!a[c]) make sense? What would it be if it is not an array?

3
  • why are you sure that a is not an array? Do you have a function signature to indicate this? If not, I am inclined to say that a is an array or an object. Commented Sep 24, 2015 at 0:40
  • Do you have any more information? This type of construct is usually how you would create a closure (advanced javascript) but there isn't a return statement anywhere. It would be great to see some more code or the context in which this takes place. Commented Sep 24, 2015 at 0:42
  • Arrays are Objects, square bracket notation works for both. Commented Sep 24, 2015 at 1:17

3 Answers 3

2

There is nothing special about that code.

It is saying, in English, If the property c of a is falsey, then the condition is true.

In JavaScript, bracket notation can be used to access properties of an object or members of an array.

For example, someArray[5] will access the 6th member of the array, while someObject['someProp'] will access someProp of the object someObject.

Sign up to request clarification or add additional context in comments.

Comments

0

The argument a is likely an object. The syntax:

if (!a[c])

Checks to see if the property in the variable c on the a object does not have a truthy value. This could be if it was null, false, undefined or any other falsey value.


The bracket notation can be used with property names. So, if you have an object like this:

var x = { name: "John"};

Then, you can access that property like in any of these ways:

x.name
x["name"];

// Or, if the property name is in a variable
var prop = "name";
x[prop]

Your example is using a version of the last of the above three options when the property name is in another Javascript variable.

Comments

0

In javascript, properties can be accessed dynamically using the square-bracket syntax.

Consider the following:

var person = {name:'Sarah'};
console.log(person.name); // logs 'Sarah';

Sometimes, you might want to dynamically access properties of an object, using a variable that holds the name of the property you want to access. The above example could also be written like this:

var person = {name:'Sarah'};
var prop = 'name';
console.log(person[prop]); // logs 'Sarah';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.