JavaScript Other Operators
1. Ternary Operator (? :)
A shortcut for if...else statements.
let age = 18;
let message = (age >= 18) ? "Adult" : "Minor";
console.log(message); // Output: Adult
Syntax:
condition ? valueIfTrue : valueIfFalse;
2. typeof Operator
Returns the type of a variable.
console.log(typeof "hello"); // Output: string
console.log(typeof 42); // Output: number
console.log(typeof true); // Output: boolean
console.log(typeof undefined); // Output: undefined
console.log(typeof null); // Output: object (this is a known
quirk in JS)
console.log(typeof {}); // Output: object
console.log(typeof []); // Output: object
3. instanceof Operator
Checks if an object is an instance of a particular class or constructor.
let arr = [1, 2, 3];
console.log(arr instanceof Array); // Output: true
console.log(arr instanceof Object); // Output: true
4. delete Operator
Removes a property from an object.
let user = { name: "Alice" , age: 25 };
delete user.age;
console.log(user); // Output: { name: "Alice" }
5. in Operator
Checks if a property exists in an object.
let person = { name: "John" , age: 30 };
console.log("age" in person); // Output: true
console.log("email" in person); // Output: false
6. void Operator
Evaluates an expression but returns undefined.
console.log(void 0); // Output: undefined
console.log(void (1 + 2)); // Output: undefined
Useful when you want to suppress a return value, especially in links or bookmarklets.
7. Comma Operator (,)
Allows multiple expressions to be evaluated, returning the last one.
let x = (1 + 2, 3 + 4);
console.log(x); // Output: 7
8. Optional Chaining Operator (?.)
Accesses deeply nested properties without throwing an error if a property doesn't exist.
let user = { name: "Alex" , address: { city: "NY" } };
console.log(user.address?.city); // Output: NY
console.log(user.contact?.email); // Output: undefined
9. Nullish Coalescing Operator (??)
Returns the right-hand value only if the left-hand is null or undefined.
let name = null;
let displayName = name ?? "Guest";
console.log(displayName); // Output: Guest
Contrast with || which also considers 0, "" , and false as falsy.
Summary Table
Operator | Purpose | Example | Output / Use |
---|---|---|---|
? : | Ternary (if-else) | age >= 18 ? "Yes" : "No" | "Yes" if age is 18+ |
typeof | Get data type | typeof 123 | "number" |
instance of | Check instance | [] instanceof Array | true |
delete | Delete object property | delete obj.key | Property removed |
in | Check if key exists in object | "key" in obj | true or false |
void | Evaluate & return undefined | void 0 | undefined |
, | Comma (multiple expressions) | (1 + 2, 3 + 4) | 7 (last result) |
?. | Optional chaining | user?.profile?.name | Safe access |
?? | Nullish coalescing | value ?? "default" | "default" if value is null/undefined |