Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How these logical operators work?

Tags:

javascript

I'm trying to understand how this line works:

var dependencies = mod && mod.dependencies || [];

This line of code exists within a function that takes mod as a parameter and mod is an object. My understanding is that first it (by the way, for the sake of precision what is "it" here? is "it" the engine?) will check if both mod and mod.dependencies resolve to true, if so, the || operator will be short circuited and mod.dependencies will return. If either are false, the empty array will return.

I don't understand, though, why it looks for both mod and mod.dependencies. Can mod.dependencies exist without mod? Why not just look for mod.dependencies?

like image 635
user4853 Avatar asked Dec 10 '22 19:12

user4853


1 Answers

This is a common technique in Javascript. It essentially creates a "fallback" in case either mod or mod.dependencies is null or undefined. The reasoning for mod && mod.dependencies is that directly addressing mod.dependencies will throw an error if mod is null. Therefore, it checks to make sure that mod is not null and (&&) mod.dependencies is not null.

The || [] part means that if either mod or mod.dependencies is null or undefined, assign dependencies to an empty array.

You can think about this kind of statement like this:

If mod is defined AND mod.dependencies is defined, use mod.dependencies. Otherwise, use an empty array ([])

like image 92
gpanders Avatar answered Jan 05 '23 00:01

gpanders