Module 6 : Operators and Expressions in javascript.
Define and identify expressions and operators
Use different types of JavaScript operators
Predict the result of complex expressions using operator precedence and associativity
Explore advanced operator usage in functional and modern JavaScript patterns
3. Core Concepts
3.1 Expressions
An expression is a valid unit of code that resolves to a value.
Types of expressions:
Arithmetic expressions: 5 + 3, x * 2
String expressions: "Hello" + " " + "World"
Logical expressions: a > b && b > c
Assignment expressions: let total = price * quantity
3.2 JavaScript Operators
Operators perform operations on variables and values.
3.2.1 Arithmetic Operators
Used for mathematical calculations.
javascript
code
let a = 10; let b = 3; console.log(a + b); // 13 console.log(a - b); // 7 console.log(a * b); // 30 console.log(a / b); // 3.333... console.log(a % b); // 1
Note: Division always returns a float.
3.2.2 Assignment Operators
Used to assign values.
javascript
code
let x = 10; x += 5; // same as x = x + 5 x -= 2; // same as x = x - 2
3.2.3 Comparison Operators
Compare two values and return a boolean.
javascript
code
console.log(5 == '5'); // true (loose equality) console.log(5 === '5'); // false (strict equality) console.log(10 != 5); // true console.log(10 > 5); // true
Tip: Always prefer === over == to avoid type coercion issues.
3.2.4 Logical Operators
Used to combine boolean values.
javascript
code
true && false // false true || false // true !true // false
3.2.5 Unary Operators
Operate on a single operand.
javascript
code
let x = 5; x++; // 6 --x; // 5 again typeof "hello"; // "string"
3.2.6 Ternary Operator
A shorthand for if-else.
javascript
code
let age = 18; let access = age >= 18 ? "Granted" : "Denied";
3.2.7 Bitwise Operators (Advanced)
Operate on binary representations.
javascript
code
5 & 1 // 1 5 | 1 // 5 5 ^ 1 // 4 ~5 // -6
3.2.8 Nullish Coalescing Operator (??)
Returns the right-hand operand when the left is null or undefined.
javascript
code
let name = null; let defaultName = name ?? "Guest"; // "Guest"
3.2.9 Optional Chaining Operator (?.)
Safely access deeply nested object properties.
javascript
code
let user = { profile: { name: "Alice" } }; console.log(user?.profile?.name); // "Alice" console.log(user?.address?.street); // undefined
4. Operator Precedence and Associativity
Precedence: Defines the order in which operators are evaluated.
Associativity: Defines the direction of operation (left-to-right or right-to-left).
Operator
Description
Associativity
()
Grouping
Left-to-right
++, --
Increment/decrement
Right-to-left
*, /, %
Multiplication/Division
Left-to-right
+, -
Addition/Subtraction
Left-to-right
=, +=, etc.
Assignment
Right-to-left
Example:
javascript
code
let result = 5 + 10 * 2; // 25, not 30
5. Examples and Pitfalls
Example 1: Operator Precedence
javascript
code
let result = 10 + 5 * 2; // 10 + (5*2) = 20
Example 2: Implicit Type Coercion
javascript
code
console.log('5' + 1); // '51' (string concatenation) console.log('5' - 1); // 4 (number subtraction)
Example 3: Logical Short-Circuiting
javascript
code
let isLoggedIn = false; console.log(isLoggedIn && "Welcome!"); // false
6. Exercises
Exercise 1: Evaluate Expressions
Predict the output before running:
javascript
code
let x = 10; let y = '5'; console.log(x + y); console.log(x - y); console.log(x == y); console.log(x === y);
Exercise 2: Use Operators
javascript
code
let a = 8; let b = 3; let result = (a * b) + (a / b); console.log(result);
Exercise 3 : Application
Write a simple login validation using logical and comparison operators:
javascript
code
let username = "admin"; let password = "1234"; let isValid = username === "admin" && password === "1234"; console.log(isValid ? "Login successful" : "Invalid credentials");
Challenge Exercise (Advanced):
Create a calculator function using switch statement that uses arithmetic operators based on input:
javascript
code
function calculator(a, b, operator) { switch (operator) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return b !== 0 ? a / b : "Cannot divide by zero"; default: return "Invalid operator"; } } console.log(calculator(10, 5, '*')); // 50
7. Topics
For advanced study, explore:
Abstract Syntax Trees (ASTs): Learn how JavaScript parses expressions.
JavaScript Engine (V8, SpiderMonkey): How operators are optimized internally.
Functional JavaScript: Use of expressions and operators in pure functions, currying, composition.
Transpilers like Babel: How complex operator behavior is transformed.
Code Obfuscation Techniques: Using operators in creative/hard-to-read ways.
8. Tips
Use live coding sessions to show operator behavior interactively.
Demonstrate console debugging to watch how expressions evaluate step-by-step.
Use codepen/jsfiddle for sandboxed demonstrations.
Provide interactive quizzes on operator precedence.
9. Summary
Expressions resolve to values.
JavaScript has a rich set of operators for different purposes.
Operator precedence and associativity affect how expressions are evaluated.
Understanding operators is essential for writing clean and bug-free code.
No comments:
Post a Comment