Note Only triggers on null/undefined, unlike || which triggers on all falsy values (0, "", false, NaN). Use ?? when 0 or empty string are valid values.
const user ={ profile:{ avatar:"pic.png"}};console.log(user?.profile?.avatar);// "pic.png"console.log(user?.settings?.theme);// undefinedconsole.log(user?.getName?.());// undefined (no error)
Note Short-circuits to undefined when a link in the chain is null/undefined. Combine with ?? for defaults: user?.name ?? "Guest"
const age =20;const category = age >=18?"adult":"minor";console.log(category);// "adult"// Nested (use sparingly)const tier = age >=65?"senior": age >=18?"adult":"minor";
Note Great for simple inline conditions. Avoid deeply nested ternaries -- they quickly become unreadable. Use if/else for complex logic.
data =[5,12,3,18,7,22]
high =[x for x in data if(doubled := x *2)>20]print(high)import re
text ="Order #12345 confirmed"if(match:= re.search(r"#(\d+)", text)):print(f"Order ID: {match.group(1)}")
Output
[12, 18, 22]
Order ID: 12345
Note The walrus operator (Python 3.8+) assigns and returns a value in one step. Most useful in while-loops, if-statements, and comprehensions to avoid repeated computation.
JS:'My cat and your dog'.match(/cat|dog/g)Py: re.findall(r'\b(?:jpg|png|gif)\b','files: logo.png and bg.jpg')
Output
JS: ["cat", "dog"]
Py: ["png", "jpg"]
Note The | operator has very low precedence -- /ab|cd/ matches 'ab' or 'cd', NOT 'a(b|c)d'. Always wrap alternations in a group when they are part of a larger pattern to avoid surprises.
// 'in' narrows based on the presence of a property
Note The 'in' operator checks if a property name exists on an object at runtime. TypeScript uses this to narrow union types. The property name must be a string literal for narrowing to work. Works well when union members have distinct unique properties.
Frequently asked questions
How does JavaScript handle in operator?
This task is covered in 4 stacks on this page: JavaScript, Python, Regular Expressions, TypeScript. The "Nullish Coalescing (??)" snippet in JavaScript uses `value ?? fallback`.
Which code does the JavaScript example use?
The "Nullish Coalescing (??)" snippet uses `value ?? fallback`, from the Data Types section of the JavaScript cheat sheet.
Which stacks cover "in operator" on this page?
JavaScript, Python, Regular Expressions, TypeScript. Together they hold 8 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Nullish Coalescing (??)": Only triggers on null/undefined, unlike || which triggers on all falsy values (0, "", false, NaN). Use ?? when 0 or empty string are valid values.