JavaScript Operators
Operators are special symbols or keywords that instruct the JavaScript engine to perform a specific action or manipulation on one or more values (called operands). Simply put, operators are what let you create, calculate, compare, and connect data in your code.
Understanding operators is fundamental, as they form the basis of all logic, calculations, and decision-making in any program.
Binary Arithmetic & Grouping Operators
Arithmetic operators are used to perform mathematical calculations.
| Operator | Description | Example | Output in the Console |
| + | Addition | 4 + 2 | 6 |
| – | Subtraction | 4 – 2 | 2 |
| * | Multiplication | 4 * 2 | 8 |
| / | Division | 4 / 2 | 2 |
| % | Remainder (Modulus) | 11 % 3 (11 / 3 = 9, 11 – 9 = 2) | 2 |
| ** | Exponentiation | 2 ** 3 | 8 |
| ( ) | Grouping Operator | A = 10; (A + 5) * 2 | 30 |
console.log(4 + 2); // Output: 6
console.log(4 - 2); // Output: 2
console.log(4 * 2); // Output: 8
console.log(4 / 2); // Output: 2
console.log(11 % 3); // Output: 2 (11/3=9, 11-9=2)
// Exponentiation Operator (Math.pow() is the same as **)
console.log(2 ** 3); // Output: 8 (2*2*2=8)
console.log(Math.pow(2,3)); // Output: 8 (2*2*2=8)
// Grouping Operator
let D = 10;
console.log((D + 5) * 2); // Output: 30JavaScriptUnary Operators (Operators on a Single Value)
A unary operator is an operator that performs an operation on a single operand.
| Operator | Description | Example | Output in the Console |
| ++ | Increment | A = 10; A ++ | 11 |
| — | Decrement | A = 10; A – – | 9 |
| + | Unary Plus | +”10″ | 10 (number) |
| – | Unary Negation | -true | -1 (number) |
console.log("\n---Increment & Decrement---");
// The let variable is used because the value is mutating (not allowed with const).
let A = 10;
let A2 = A++; // Increment "A" by 1
console.log(A); // Output: 11
console.log(A2); // Output: 10 (wasn't incremented)
console.log(++A); // Output: 12
let B = 10;
let B2 = ++B; // Increment before B2 set to 10 adds 1
console.log(B); // Output: 11
console.log(B2); // Output: 11
console.log(++B); // Output: 12
// Decrement Example
let C = 10;
console.log("C = " + --C); // Output: C = 9
console.log("\n---Unary Plus---");
console.log(+10); // Output: 10
console.log(+"10"); // Output: 10 (number)
console.log(+true); // Output: 1
console.log(+false); // Output: 0
console.log(+"test"); // Output: NaN
console.log(+null); // Output: 0
console.log(+undefined); // Output: NaN
console.log(+[]); // Output: 0
// Treats array as containing a number, 0 if no number, NaN if text in array)
console.log(+{}); // Output: NaN (objects to primitive - converts to string)
console.log("\n---Unary Negation---");
console.log(-10); // Output: -10
console.log(-"10"); // Output: -10 (number)
console.log(-true); // Output: -1
console.log(-false); // Output: -0
console.log(-"test"); // Output: NaN
console.log(-null); // Output: -0
console.log(-undefined); // Output: NaN
console.log(-[]); // Output: -0
// Treats array as containing a number, 0 if no number, NaN if text in array)
console.log(-{}); // Output: NaN (objects to primitive - converts to string)JavaScriptAssignment Operators
Assignment operators are used to assign a value to a variable. The most basic is the simple assignment operator (=), but JavaScript provides shorthand operators for combining calculation and assignment.
| Operator | Description | Example | Output in the Console |
| = | Assignment | A = 5 (Used in examples below) | 5 |
| += | Addition Assignment | A += 10 | 15 |
| -= | Subtraction Assignment | A -= 11 | 6 |
| *= | Multiplication Assignment | A *= 4 | 20 |
| /= | Division Assignment | A /= 2 | 2.5 |
| %= | Remainder Assignment | A %= 2 (5 / 2 = 4, 5 – 4 = 1) | 1 |
| **= | Exponentiation Assignment | A **= 3 (5 x 5 x 5 = 125) | 125 |
// Note: Compound assignment operators (like +=) mutate the variable.
// The next line calculates based on the previous result, not on 5.
// So "A = 5" needs to be reset between lines for the desired output.
A = 5
A += 10; // Output: 15
A -= 11; // Output: -6
A *= 4; // Output: 20
A /= 2; // Output: 2.5
A %= 2; // Output: 1 (5/2=4, 5-4=1)
A **= 3; // Output: 125 (5x5x5=125)JavaScriptComparison Operators
Comparison operators are used to compare two values and always return a Boolean (true or false).
| Operator | Description | Example | Output in the Console |
| == | Loose Equality Checks if values are equal. Allows type coercion (JS will try to convert types to make them match). | 1 == ‘1’ | true |
| === | Strict Equality Checks if values AND data types are equal. No type coercion allowed. (The recommended standard.) | 1 === ‘1’ | false |
| != | Loose Inequality Checks if values are not equal (allows coercion). | 1 != 2 | true |
| !== | Strict Inequality Checks if values OR data types are not equal. | 1 !== 1 | false |
console.log("\n---------Loose Equality-------------");
// Equality (Loose Equality)
console.log(5 == "5"); // Output: true (string "5" is coerced to number 5)
console.log(0 == false); // Output: true (boolean false is coerced to number 0)
console.log(1 == true); // Output: true (boolean true is coerced to number 1)
console.log(null == undefined); // Output: true (special case, null and undefined are loosely equal)
console.log("hello" == "Hello"); // Output: false (case-sensitive string comparison)
console.log([1, 2] == "1,2"); // Output: true (array is coerced to string "1,2")
console.log("\n---------Strict Equality-------------");
// Strict Equality
console.log(5 === "5"); // Output: false (number vs. string)
console.log(0 === false); // Output: false (number vs. boolean)
console.log(1 === true); // Output: false (number vs. boolean)
console.log(null === undefined); // Output: false (different types)
console.log("hello" === "hello"); // Output: true (same value and type)
console.log([1, 2] === "1,2"); // Output: false (array vs. string)
console.log(NaN === NaN); // Output: false (NaN is never strictly equal to itself)
console.log(+0 === -0); // Output: true (signed zeros are strictly equal)
// The plus and minus signs explicitly define the zero's positive or negative "direction" to demonstrate that JavaScript's strict equality operator ignores this difference and treats them as the exact same value.
// Empty Strings, Zero, and Equality
// Loose Equality gives empty strings and strings with spaces a value of 0.
console.log("" == 0); // Output: true (Empty string becomes 0)
console.log(" " == 0); // Output: true (String with spaces also becomes 0)
// Loose Equality treats a string with "0" the same as the number 0.
console.log("0" == false); // Output: true ("0" -> 0 -> false)
// Strict Equality treats the string differently than the number.
console.log("" === 0); // Output: false (Different types)
console.log("\n---------Super Strict Equality-------------");
// SUPER Strict Equality with Object.is()
console.log(NaN === NaN); // Output: false (since Not a Number is not equal to anything)
console.log(Object.is(NaN, NaN)); // Output: true (The truth)
// Better way (for reference) to check is something is NaN
console.log(Number.isNaN(NaN)); // Output: true
console.log(Number.isNaN("hello")); // Output: false
// A solution for the -0 and +0 being numerically equivalent
console.log(+0 === -0); // Output: true (The lie - as seen above)
console.log(Object.is(+0, -0)); // Output: false (The truth - they are different)
console.log("\n---------Inequality & Strict Inequality-------------");
// Inequality != & Strict Inequality !== are the oposite of == and ===
console.log(1 != "1"); // false (1 is coerced to "1", then compared, so they are considered equal)
console.log(5 != 10); // true (5 is not equal to 10)
console.log(1 !== "1"); // true (value is the same, but types are different: number vs. string)
console.log(5 !== 10); // true (values are different)
console.log(7 !== 7); // false (value and type are both the same)
console.log("\n---------Array Equality-------------");
// Array Equality
console.log([1,2,3] == [1,2,3]); // Output: false
const arrayOne = [1,2,3]
const arrayTwo = [1,2,3]
console.log(arrayOne == arrayTwo); // Output: false
const arrayThree = arrayOne // Assign arrayOne to arrayThree
console.log(arrayOne == arrayThree); // Output: true (compares the variable address in memory instead of the value to get "true")
console.log(arrayOne === arrayThree); // Output: true (works with strict equality too)
const arrayFour = ["1","2","3"] // Array with strings
console.log(arrayOne === arrayFour); // Output: false
// Arrays with one item imply that item in loose equality
console.log([10] == 10); // Output: true (Array converts to "10", then to 10)
console.log(["10"] == 10); // Output: true
console.log("\n----------Object Equality------------");
// Object Equality
console.log({1:"one"} == {1:"one"}); // Output: false
const objOne = {1:"one"}
const objTwo = {1:"one"}
console.log(objOne == objTwo); // Output: false
const objThree = objOne
console.log(objOne == objThree); // Output: true
console.log("\n----------IF Statement------------");
// Check equality with an IF statement
const checkEquality = "10"
if (checkEquality === 10) {
console.log("True. This is equal.");
} else {
console.log("False. This is NOT equal.");
}
// Output: False. This is NOT equal.JavaScriptRelational Operators
Relational operators are used to determine the relationship between two values, checking if one is greater than, less than, or equal to the other. They always return a Boolean value (true or false).
| Operator | Description | Example | Output in the Console |
| > | Greater than | 5 > 5 | false |
| < | Less than | 5 < 5 | false |
| >= | Greater than or equal to | 5 >= 5 | true |
| <= | Less than or equal to | 5 <= 5 | true |
console.log(5 > 5); //Output: false
console.log(5 >= 5); //Output: true
console.log(5 < 5); //Output: false
console.log(5 <= 5); //Output: true
const myString = "String!"
console.log("String!".length); //Output: 7
console.log(myString.length > 6); //Output: true
// null acts like 0 in math, but not in equality.
console.log(Number(null)); // Output: 0 (So you might think null == 0...)
console.log(null == 0); // Output: false (null is only loosely equal to undefined, nothing else)
console.log(null > 0); // Output: false
console.log(null < 0); // Output: false
console.log(null >= 0); // Output: true (">=" coerces null to 0.)JavaScriptLogical & Ternary Operators
Logical operators are used to combine or modify Boolean (true/false) values. They are essential for creating complex conditions in if/else statements. Ternary operators simplify if/else statements.
- && Short-circuits (stops) when it finds a False.
- || Short-circuits (stops) when it finds a True.
- ?? assigns a default value to a variable when the original value is null or undefined.
- ! inverts truthy and falsy data.
!!variableis a trick to convert data to a puretrue/false.- ?: is shorthand for writing if/else statements.
| Operator | Description | Example | Output in the Console |
| && | AND | false && true | false |
| || | OR | false || true | true |
| ?? | Nullish Coalescing Operator | null ?? “Default Value” | Default Value |
| ?. | Optional Chaining Operator | const user1 = { name: “Becky”, details: { address: { city: “New York” } }}; console.log(user1.details?.address?.city); | New York |
| ! | NOT | !true | false |
| !! | Double Negation Operator | !!0 | false |
| ? : | Ternary Operator/Statement The Ternary Operator ( ? :) is a concise shorthand for writing a simple if/else conditional statement. | const isTrue = true; console.log(isTrue ? “It’s true” : “It’s false”); | It’s true |
// AND && OPERATOR
console.log("\n---Truthy/Falsy---");
// True/False Logic:
console.log(true && true) // Output: true
console.log(true && false) // Output: false
console.log(false && true) // Output: false (short-circuits - false first)
console.log(false && false) // Output: false (short-circuits - false first)
console.log("\n---Truthy/Falsy && Short Circuiting---");
// Truthy/Falsy Values (Short Circuiting)
console.log("test" && 123) // Output: 123 (both are truthy, returns the last one)
console.log(123 && "test") // Output: hello (both are truthy, returns the last one)
console.log(0 && 1) // Output: 0 (0 is falsy, returns the first falsy value)
console.log(null && "test") // Output: null (null is falsy, returns the first falsy value)
console.log(undefined && 10) // Output: undefined (undefined is falsy, returns the first falsy value)
// Chains
console.log(1 && "test" && 3 && 4); // Output: 4 (All are truthy, returns the last one)
console.log(1 && 0 && 3 && 4); // Output: 0 (Hits the first falsy and STOPS. 3 and 4 are ignored.)
console.log("\n---Short Circuiting Guard Clause---");
const user = undefined;
// If a user is not defined and referenced it will crash:
// console.log(user.name); // Output: Error - Cannot read property 'name' of undefined
// If short circuiting is used but user is not defined, it doesn't crash:
console.log(user && user.name); // Output: undefined
// Explanation: Because 'user' is falsy, it stops. It NEVER tries to read 'user.name'.
// Works with null as well:
const noUser = null;
console.log(noUser && noUser.name); // Output: null (no error)
// Object name value example without undefined or null:
const userInfo = { name: "Bill" };
console.log(userInfo && userInfo.name); // Output: "Bill"
console.log("\n---IF Example---");
// IF Statement with two conditions compared with &&
// IF both conditions are true, it will log true, else false.
if (1 > 0 && 2 < 3) {
console.log(true);
} else {
console.log(false);
}
// Output: trueJavaScript// OR || OPERATOR
console.log("\n---Truthy/Falsy---");
// True/False Logic:
console.log(true || true); // Output: true
console.log(true || false); // Output: true (short-circuits - found true immediately)
console.log(false || true); // Output: true
console.log(false || false); // Output: false (both are false)
// Rule: Returns the FIRST Truthy value it finds. If none, returns the LAST value.
console.log(10 || 20); // Output: 10 (10 is truthy, so it stops there)
console.log(0 || 50); // Output: 50 (0 is falsy, moves to next)
console.log("Hello" || "World"); // Output: "Hello"
console.log("" || "Backup"); // Output: "Backup" (Empty string is falsy)
console.log(null || "Default"); // Output: "Default" (null is falsy)
console.log(undefined || null || "Third Option"); // Output: "Third Option" (undefined and null are falsy)
console.log(0 || "Hey" || "Now"); // Output: Hey (first truthy value)
console.log("\n---Setting Defaults with OR---");
// Scenario: A user didn't set a name, so we use a fallback.
const userName = ""; // User left it blank (falsy)
const displayName = userName || "Anonymous User";
console.log(displayName); // Output: "Anonymous User"
// Scenario: User DID set a name
const realName = "Bob";
console.log(realName || "Anonymous User"); // Output: "Bob" (truthy)
// ERROR Scenario: initalizing a value to 0 (falsy)
const score = 0;
const finalScore = score || "Game Over";
console.log(finalScore); // Output: "Game Over" (truthy - instead of score total)
// Truthy/Falsy Example with a function:
function greet(name) {
name = name || "New User"; // If 'name' is falsy, assign "New User"
console.log(`Hello, ${name}!`);
}
greet("Rodney"); // Output: Hello, Rodney!
greet(null); // Output: Hello, New User!
greet(""); // Output: Hello, New User!JavaScript// ?? Nullish Coalescing Operator
let number = null;
number = undefined; // remove to see same result for null.
const myNumber = number ?? "Add a number";
console.log(myNumber); // Output: Add a number
// 0 and "" empty string would work because they are falsy instead of null or undefined.
// Nullish Object Value Example
let userSettings = { theme: null, language: "en" };
const selectedTheme = userSettings.theme ?? "dark";
const selectedLanguage = userSettings.language ?? "default";
console.log(`Theme: ${selectedTheme}, Language: ${selectedLanguage}`);
// Output: Theme: dark, Language: enJavaScript// ?. Optional Chaining Operator
const user1 = {
name: "Becky",
details: { address: { city: "New York" } }
};
const user2 = {
name: "Bob",
details: null // Bob has no details
};
// Standard Access
console.log(user1.details?.address?.city); // Output: "New York"
// With '?.', it sees 'details' is null, stops, and returns undefined.
console.log(user2.details?.address?.city); // Output: undefined
/*
Without '?.', this line below would crash the entire program.
The "address" property can't be accessed so an error would occur:
console.log(user2.details.address.city); // Uncaught TypeError
It isn't just for "Object Literals" ({}). It works anywhere you would normally access data:
thing?.prop
thing?.[index]
thing?.()
*/JavaScript// ! Logical NOT Operator
console.log(!true); // Output: false
console.log(!false); // Output: true
console.log("\n---Truthy Inversion---");
// Rule: Anything "real" becomes false when inverted
console.log(!5); // Output: false (5 is truthy)
console.log(!"0"); // Output: false ("0" string is truthy - watch out!)
console.log(!"test"); // Output: false ("test" is truthy)
console.log(!{}); // Output: false (An empty object is truthy)
console.log(![]); // Output: false (An empty array is truthy)
console.log("\n---Falsy Inversion---");
// Rule: Anything "empty" or zero becomes true when inverted
console.log(!0); // Output: true (0 is falsy)
console.log(!""); // Output: true (An empty string is falsy)
console.log(!null); // Output: true (null is falsy)
console.log(!undefined); // Output: true (undefined is falsy)
console.log(!NaN); // Output: true (NaN is falsy)
console.log("\n---IF Statements---");
// 1. Inverting a specific boolean
const isLoading = false;
if (!isLoading) {
console.log("Page is ready to show.");
}
// 2. The "Guard Clause" (Checking if something is missing)
const userProfileImage = null;
if (!userProfileImage) {
console.log("No user profile image found, add a new photo.");
}JavaScript// !! Double Negation Operator
// Negates the result of the first ! and converts to it's boolean representation.
console.log("\n---Truthy Values to True---");
console.log(!!true); // Output: true
console.log(!!1); // Output: true
console.log(!!'test'); // Output: true
console.log(!!{}); // Output: true (empty object is truthy)
console.log(!![]); // Output: true (empty array is truthy)
console.log(!!Infinity); // Output: true
console.log("\n---Falsy Values to False---");
console.log(!!false); // Output: false
console.log(!!0); // Output: false
console.log(!!""); // Output: false (empty string is falsy)
console.log(!!null); // Output: false
console.log(!!undefined); // Output: false
console.log(!!NaN); // Output: false
// The Boolean() method has the same effect:
console.log("Boolean method: " + Boolean(1)); // Output: Boolean method: true
console.log("Boolean method: " + Boolean(0)); // Output: Boolean method: falseJavaScript// ?: Ternary Operator
// condition ? expressionIfTrue : expressionIfFalse;
const isActive = true;
const className = isActive ? "active-item" : "inactive-item";
console.log(className); // Output: active-item
let personAge = 20;
let isDrinkingLegal = (personAge >= 21) ? "Can't Drink" : "Can Drink";
console.log(isDrinkingLegal); // Output: Can Drink
// Returning a value from a function
const isVotingLegal = (voterAge) => {
return (voterAge >= 18) ? "Can Vote" : "Can't Vote";
};
console.log(isVotingLegal(18)); // Output: Can VoteJavaScriptLogical Assignment Operators
JavaScript offers three logical assignment operators, which combine a logical operation with an assignment.
- Logical OR Assignment (
||=): This operator assigns the right-hand side value to the left-hand side variable only if the left-hand side is a falsy value (e.g.,false,0,null,undefined,'',NaN). - Logical AND Assignment (
&&=): This operator assigns the right-hand side value to the left-hand side variable only if the left-hand side is a truthy value. - Nullish Coalescing Assignment (
??=): This operator assigns the right-hand side value to the left-hand side variable only if the left-hand side isnullorundefined. Unlike||=, it does not assign if the left-hand side is other falsy values like0or''.
Note: these operators can never be used with const because they are dependent on reassignment.
| Operator | Description | Example | Output in the Console |
| &&= | Logical AND Assignment Assign if Truthy | let x = 1 x &&= “Truthy” console.log(x); | Truthy |
| ||= | Logical OR Assignment Assign if Falsy | let x = 0 x ||= “Falsy” console.log(x); | Falsy |
| ??= | Nullish Coalescing Assignment Assign if Null or Undefined | let x = null x ??= “Null or Undef.” console.log(x); | Null or Undef. |
// &&= Logical AND Assignment (Set IF value truthy then assign)
let isTruthy = 1; // Truthy value
isTruthy &&= "Truthy";
console.log(isTruthy); // Output: Truthy
let isTruthy2 = 0; // Falsy value
isTruthy2 &&= "Truthy";
console.log(isTruthy2); // Output: 0
// ||= Logical OR Assignment (Set IF value falsy then assign)
let isFalsy = 1; // Truthy value
isFalsy ||= "Falsy";
console.log(isFalsy); // Output: 1
let isFalsy2 = 0; // Falsy value
isFalsy2 ||= "Falsy";
console.log(isFalsy2); // Output: Falsy
// ??= Nullish Coalescing Assignment (Set IF value null or undefined)
let isNullUndefined = null; // null or undefined value
isNullUndefined ??= "Nullish";
console.log(isNullUndefined); // Output: Nullish
let isFontPreferenceSet = undefined; // null or undefined value
isFontPreferenceSet ??= "font-family: Arial, sans-serif;";
console.log(isFontPreferenceSet); // Output: font-family: Arial, sans-serif;
// ??= respects falsy values: 0, false, NaN, and " " empty strings.JavaScriptBitwise Assignment Operators
JavaScript bitwise operators perform operations directly on the binary representation (individual bits) of 32-bit signed integers, treating numbers as sequences of 0s and 1s rather than their decimal values. These operators include AND (&), OR (|), XOR (^), NOT (~), and various shift operators (<<, >>, >>>), allowing for low-level manipulation of data at the bit level.
| Operator | Description | Description | Example |
| & | AND | Sets each bit to 1 if both corresponding bits are 1; otherwise, it’s 0. | (5 & 7)yields 5 (binary 0101) |
| | | OR | Sets each bit to 1 if at least one of the corresponding bits is 1; otherwise, it’s 0. | (5 | 7) yields 7 (binary 0111) |
| ^ | XOR | Sets each bit to 1 if the corresponding bits are different; otherwise, it’s 0. | (5 ^ 7)yields 2 (binary 0010) |
| ~ | NOT | Inverts all the bits of its single operand (unary operator). | (~5)yields -6 (in 32-bit signed integer representation) |
| << | Left Shift | Shifts the bits of the left operand to the left by the number of places specified by the right operand, filling new positions with zeros. | (5 << 1)yields 10 (effectively 5 * 2^1) |
| >> | Signed Right Shift | Shifts the bits of the left operand to the right by the number of places specified by the right operand. | (5 >> 1)yields 2 (effectively 5 / 2^1) |
| >>> | Zero Fill Right Shift | Shifts the bits of the first operand to the right, filling the left with zeros, regardless of the sign bit. | (5 >>> 1)yields 2 (effectively 5 / 2^1). |
| >>= | Signed Right Shift Assignment | This operator performs a signed right shift on the left operand by the number of bits specified in the right operand, and then assigns the result back to the left operand. It’s equivalent to x = x >> y. The sign bit is preserved during the shift, meaning negative numbers remain negative. | (10 >>= 2)yields 2 |
| >>>= | Unsigned Right Shift Assignment | This operator performs an unsigned right shift on the left operand by the number of bits specified in the right operand, and then assigns the result back to the left operand. It’s equivalent to x = x >>> y. This operator treats the left operand as an unsigned 32-bit integer, filling the leftmost bits with zeros regardless of the original sign. | (10 >>>= 2)yields 2 |
Bitwise operators are considered advanced in JavaScript and are typically not necessary for the web development tasks that constitute most of the language’s use cases, nor for general application logic which handles floating-point numbers by default. Here are some basic examples of finding the binary representation of numbers and using bitwise operators:
const decimalNumber = 4; // Add a number for the binary representation
const binaryString = decimalNumber.toString(2);
console.log(binaryString); // Output: "100"
/*-- The number 2 represents the Base (Radix) that you want to convert the number into.
Since Binary is a Base-2 system (it only uses two digits: 0 and 1), passing 2 tells JavaScript: "Please rewrite this number using only 0s and 1s." --*/
// Bitwise & AND Operator (Check if number is even)
function isEven(num) {
return (num & 1) === 0;
}
console.log(isEven(4)); // Output: true
console.log(isEven(7)); // Output: false
// This works because the number on the far right of a binary representation of a number will always be 0 if it's an even number (i.e 2 = 010, 4 = 100, 6 = 110)
// Double Bitwise ~~ NOT Operator (truncate positive numbers like Math.floor())
const floatNum = 5.7;
const truncatedNum = ~~floatNum;
console.log(truncatedNum); // Output: 5
const negativeFloatNum = -3.2;
const truncatedNegativeNum = ~~negativeFloatNum;
console.log(truncatedNegativeNum); // Output: -3
// (Note: Differs from Math.floor(-3.2) which is -4) and only works up to the number 2 billion (due to only using 32 bits in JS bitwise operators instead of 64 bits with JS numbers (that Math.floor() would work with).JavaScriptType Operators
JavaScript includes two primary type operators used to determine or check the type of a value or object: typeof and instanceof operator.
| Operator | Description | Example | Output in the Console |
typeof | This operator returns a string indicating the data type of its operand. It is particularly useful for checking primitive types and functions (as seen in the data types lesson). | console.log(typeof 123); | number |
instanceof(advanced topic) | This operator checks if an object is an instance of a particular constructor function or class, or if it inherits from that constructor’s prototype chain. It returns true or false. It is primarily used for objects and inheritance. | See source code below. | See source code below. |
// typeof Operator Examples:
console.log(typeof "hello"); // string
console.log(typeof 123); // number
console.log(typeof true); // boolean
console.log(typeof undefined); // undefined
console.log(typeof null); // object (Note: This is a known quirk in JavaScript)
console.log(typeof {}); // object
console.log(typeof []); // object
console.log(typeof function() {}); // function
// instanceof Operator Examples:
let today = new Date();
let userAge = 25;
console.log(numbers instanceof Date);
// Output: true (Yes, it was created using the Date() constructor)
console.log(userAge instanceof Object);
// Output: false (Primitives like numbers, strings, etc., are not objects)JavaScriptAdvanced: The instanceof operator is most commonly used to check objects created from your own custom classes.
// Blueprint (Constructor/Class) for a Vehicle
class Vehicle {
constructor(wheels) {
this.wheels = wheels;
}
}
// Blueprint for a specialized Car
class Car extends Vehicle {
constructor(make) {
super(4); // Calls Vehicle constructor with 4
this.make = make;
}
}
let honda = new Car("Honda");
let bike = new Vehicle(2);
// Check #1: Was 'honda' built from the Car class?
console.log(honda instanceof Car);
// Output: true
// Check #2: Was 'honda' built from the Vehicle class?
console.log(honda instanceof Vehicle);
// Output: true (This shows the prototype chain—a Car IS A Vehicle)
// Check #3: Was 'bike' built from the Car class?
console.log(bike instanceof Car);
// Output: false (A Vehicle is NOT necessarily a Car)JavaScriptFinal thought: Operators are the action words of JavaScript. By mastering these symbols, you gain the power to handle all arithmetic, data comparison, and logical decision-making, making them the backbone of your program’s intelligence.




