- JavaScript Introduction
- JavaScript Where To
- JavaScript Output
- JavaScript Statements
- JavaScript Syntax
- JavaScript Comments
- JavaScript Variables
- JavaScript Let
- JavaScript Const
- JavaScript Operators
- JavaScript Assignment
- JavaScript Data Types
- JavaScript Functions
- JavaScript Objects
- JavaScript Events
- JavaScript Strings
- JavaScript String Methods
- JavaScript Numbers
- JavaScript Number Methods
- JavaScript Arrays
- JavaScript Array Const
- JavaScript Array Methods
- JavaScript Sorting Arrays
- JavaScript Array Iteration
- JavaScript Date Objects
- JavaScript Date Formats
- JavaScript Get Date Methods
- JavaScript Set Date Methods
- JavaScript Math Object
- JavaScript Random
- JavaScript Booleans
- JavaScript Comparison And Logical Operators
- JavaScript If Else And Else If
- JavaScript Switch Statement
- JavaScript For Loop
- JavaScript Break And Continue
- JavaScript Type Conversion
- JavaScript Bitwise Operations
- JavaScript Regular Expressions
- JavaScript Errors
- JavaScript Scope
- JavaScript Hoisting
- JavaScript Use Strict
- The JavaScript This Keyword
- JavaScript Arrow Function
- JavaScript Classes
- JavaScript JSON
- JavaScript Debugging
- JavaScript Style Guide
- JavaScript Common Mistakes
- JavaScript Performance
- JavaScript Reserved Words
- JavaScript Versions
- JavaScript History
- JavaScript Forms
- JavaScript Validation API
- JavaScript Objects
- JavaScript Object Properties
- JavaScript Function Definitions
- JavaScript Function Parameters
- JavaScript Function Invocation
- JavaScript Closures
- JavaScript Classes
- Java Script Async
- JavaScript HTML DOM
- The Browser Object Model
- JS Ajax
- JavaScript JSON
- JavaScript Web APIs
- JS Vs JQuery
JavaScript Operators
JavaScript Operators
JavaScript operators are symbols used to perform operations on variables and values. They are categorized into several types, such as arithmetic operators, assignment operators, comparison operators, logical operators, and more. These operators are crucial for performing calculations, making decisions, and manipulating data in JavaScript.
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations like addition, subtraction, multiplication, division, and more.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Arithmetic Operators</title>
</head>
<body>
<script>
let x = 10;
let y = 5;
let addition = x + y;
let subtraction = x - y;
let multiplication = x * y;
let division = x / y;
console.log("Addition:", addition); // Output: 15
console.log("Subtraction:", subtraction); // Output: 5
console.log("Multiplication:", multiplication); // Output: 50
console.log("Division:", division); // Output: 2
</script>
</body>
</html>
Assignment Operators
Assignment operators are used to assign values to variables.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Assignment Operators</title>
</head>
<body>
<script>
let x = 10;
x += 5; // Equivalent to: x = x + 5
console.log("Updated x:", x); // Output: 15
</script>
</body>
</html>
Comparison Operators
Comparison operators are used to compare values and return true or false.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Comparison Operators</title>
</head>
<body>
<script>
let a = 10;
let b = 5;
console.log("a > b:", a > b); // Output: true
console.log("a < b:", a < b); // Output: false
console.log("a === b:", a === b); // Output: false (strict equality)
console.log("a !== b:", a !== b); // Output: true (strict inequality)
</script>
</body>
</html>
Logical Operators
Logical operators are used to combine conditional statements.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Logical Operators</title>
</head>
<body>
<script>
let x = 10;
let y = 5;
let z = 15;
console.log("x > y && x < z:", x > y && x < z); // Output: true (both conditions are true)
console.log("x > y || x > z:", x > y || x > z); // Output: true (at least one condition is true)
console.log("!(x > y):", !(x > y)); // Output: false (negation of true is false)
</script>
</body>
</html>
Conditional (Ternary) Operator
The conditional operator (ternary operator) is used for conditional expressions.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Conditional Operator</title>
</head>
<body>
<script>
let age = 18;
let message = (age >= 18) ? "You are an adult" : "You are a minor";
console.log(message); // Output: "You are an adult"
</script>
</body>
</html>
String Concatenation Operator
The plus operator (+) can also be used for string concatenation.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>String Concatenation Operator</title>
</head>
<body>
<script>
let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName;
console.log("Full Name:", fullName); // Output: "John Doe"
</script>
</body>
</html>
Bitwise Operators
Bitwise operators perform bitwise operations on integers.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bitwise Operators</title>
</head>
<body>
<script>
let a = 5; // Binary: 0101
let b = 3; // Binary: 0011
console.log("a & b:", a & b); // Output: 1 (AND)
console.log("a | b:", a | b); // Output: 7 (OR)
console.log("a ^ b:", a ^ b); // Output: 6 (XOR)
console.log("~a:", ~a); // Output: -6 (NOT)
console.log("a << 1:", a << 1); // Output: 10 (left shift)
console.log("a >> 1:", a >> 1); // Output: 2 (right shift)
</script>
</body>
</html>
These examples showcase different JavaScript operators and how they can be used in HTML documents to perform various operations on data and variables.
Practice Excercise Practice now
JavaScript Arithmetic Operators
JavaScript operators are essential tools that allow you to manipulate data and perform various operations within HTML documents. These operators can be classified into several categories: arithmetic, assignment, comparison, logical, bitwise, and others. Below is an overview of these operators with examples, embedded within HTML to illustrate their practical use.
1. Arithmetic Operators
Arithmetic operators are used to perform mathematical calculations.
- Addition (+)
- Subtraction (-)
- Multiplication (*)
- Division (/)
- Modulus (%)
- Exponentiation (**)
- Increment (++)
- Decrement (--)
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Arithmetic Operators</title>
<script>
function performArithmetic() {
var a = 10;
var b = 3;
document.getElementById("addition").innerHTML = "a + b = " + (a + b);
document.getElementById("subtraction").innerHTML = "a - b = " + (a - b);
document.getElementById("multiplication").innerHTML = "a * b = " + (a * b);
document.getElementById("division").innerHTML = "a / b = " + (a / b);
document.getElementById("modulus").innerHTML = "a % b = " + (a % b);
document.getElementById("exponentiation").innerHTML = "a ** b = " + (a ** b);
a++;
document.getElementById("increment").innerHTML = "a++ = " + a;
b--;
document.getElementById("decrement").innerHTML = "b-- = " + b;
}
</script>
</head>
<body onload="performArithmetic()">
<h1>JavaScript Arithmetic Operators</h1>
<p id="addition"></p>
<p id="subtraction"></p>
<p id="multiplication"></p>
<p id="division"></p>
<p id="modulus"></p>
<p id="exponentiation"></p>
<p id="increment"></p>
<p id="decrement"></p>
</body>
</html>
2. Assignment Operators
Assignment operators assign values to JavaScript variables.
- Assignment (=)
- Addition assignment (+=)
- Subtraction assignment (-=)
- Multiplication assignment (*=)
- Division assignment (/=)
- Modulus assignment (%=)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Assignment Operators</title>
<script>
function performAssignment() {
var x = 10;
document.getElementById("assignment").innerHTML = "x = " + x;
x += 5;
document.getElementById("additionAssignment").innerHTML = "x += 5 = " + x;
x -= 3;
document.getElementById("subtractionAssignment").innerHTML = "x -= 3 = " + x;
x *= 2;
document.getElementById("multiplicationAssignment").innerHTML = "x *= 2 = " + x;
x /= 4;
document.getElementById("divisionAssignment").innerHTML = "x /= 4 = " + x;
x %= 3;
document.getElementById("modulusAssignment").innerHTML = "x %= 3 = " + x;
}
</script>
</head>
<body onload="performAssignment()">
<h1>JavaScript Assignment Operators</h1>
<p id="assignment"></p>
<p id="additionAssignment"></p>
<p id="subtractionAssignment"></p>
<p id="multiplicationAssignment"></p>
<p id="divisionAssignment"></p>
<p id="modulusAssignment"></p>
</body>
</html>
3. Comparison Operators
Comparison operators compare two values and return a boolean value (true or false).
- Equal (==)
- Strict equal (===)
- Not equal (!=)
- Strict not equal (!==)
- Greater than (>)
- Greater than or equal (>=)
- Less than (<)
- Less than or equal (<=)
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Comparison Operators</title>
<script>
function performComparison() {
var a = 5;
var b = "5";
document.getElementById("equal").innerHTML = "a == b: " + (a == b);
document.getElementById("strictEqual").innerHTML = "a === b: " + (a === b);
document.getElementById("notEqual").innerHTML = "a != b: " + (a != b);
document.getElementById("strictNotEqual").innerHTML = "a !== b: " + (a !== b);
document.getElementById("greaterThan").innerHTML = "a > b: " + (a > b);
document.getElementById("greaterThanOrEqual").innerHTML = "a >= b: " + (a >= b);
document.getElementById("lessThan").innerHTML = "a < b: " + (a < b);
document.getElementById("lessThanOrEqual").innerHTML = "a <= b: " + (a <= b);
}
</script>
</head>
<body onload="performComparison()">
<h1>JavaScript Comparison Operators</h1>
<p id="equal"></p>
<p id="strictEqual"></p>
<p id="notEqual"></p>
<p id="strictNotEqual"></p>
<p id="greaterThan"></p>
<p id="greaterThanOrEqual"></p>
<p id="lessThan"></p>
<p id="lessThanOrEqual"></p>
</body>
</html>
4. Logical Operators
Logical operators are used to combine multiple comparison operators.
- Logical AND (&&)
- Logical OR (||)
- Logical NOT (!)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Logical Operators</title>
<script>
function performLogical() {
var a = true;
var b = false;
document.getElementById("and").innerHTML = "a && b: " + (a && b);
document.getElementById("or").innerHTML = "a || b: " + (a || b);
document.getElementById("notA").innerHTML = "!a: " + (!a);
document.getElementById("notB").innerHTML = "!b: " + (!b);
}
</script>
</head>
<body onload="performLogical()">
<h1>JavaScript Logical Operators</h1>
<p id="and"></p>
<p id="or"></p>
<p id="notA"></p>
<p id="notB"></p>
</body>
</html>
5. Bitwise Operators
Bitwise operators perform operations on the binary representations of numbers.
- Bitwise AND (&)
- Bitwise OR (|)
- Bitwise XOR (^)
- Bitwise NOT (~)
- Left shift (<<)
- Right shift (>>)
- Unsigned right shift (>>>)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Bitwise Operators</title>
<script>
function performBitwise() {
var a = 5; // 0101 in binary
var b = 1; // 0001 in binary
document.getElementById("and").innerHTML = "a & b: " + (a & b); // 0001 (1)
document.getElementById("or").innerHTML = "a | b: " + (a | b); // 0101 (5)
document.getElementById("xor").innerHTML = "a ^ b: " + (a ^ b); // 0100 (4)
document.getElementById("not").innerHTML = "~a: " + (~a); // 1010 (-6)
document.getElementById("leftShift").innerHTML = "a << b: " + (a << b); // 1010 (10)
document.getElementById("rightShift").innerHTML = "a >> b: " + (a >> b); // 0010 (2)
document.getElementById("unsignedRightShift").innerHTML = "a >>> b: " + (a >>> b); // 0010 (2)
}
</script>
</head>
<body onload="performBitwise()">
<h1>JavaScript Bitwise Operators</h1>
<p id="and"></p>
<p id="or"></p>
<p id="xor"></p>
<p id="not"></p>
<p id="leftShift"></p>
<p id="rightShift"></p>
<p id="unsignedRightShift"></p>
</body>
</html>
6. Other Operators
Other operators include the ternary operator and the typeof operator.
- Ternary (? :): A shorthand for if-else statements.
- typeof: Returns the type of a variable.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Other Operators</title>
<script>
function performOtherOperations() {
var a = 5;
var b = "hello";
var result = (a > 2) ? "a is greater than 2" : "a is not greater than 2";
document.getElementById("ternary").innerHTML = result;
document.getElementById("typeofA").innerHTML = "typeof a: " + (typeof a);
document.getElementById("typeofB").innerHTML = "typeof b: " + (typeof b);
}
</script>
</head>
<body onload="performOtherOperations()">
<h1>JavaScript Other Operators</h1>
<p id="ternary"></p>
<p id="typeofA"></p>
<p id="typeofB"></p>
</body>
</html>
Practice Excercise Practice now
JavaScript Assignment Operators
JavaScript assignment operators are used to assign values to variables. They perform basic operations and store the results in variables. Here are the most commonly used assignment operators in JavaScript, along with examples to illustrate their usage.
Basic Assignment Operator
= (Assignment)
The assignment operator = assigns the value on the right to the variable on the left.
let a = 10; // a is assigned the value 10
let b = 'hello'; // b is assigned the value 'hello'
Arithmetic Assignment Operators
Arithmetic assignment operators combine an arithmetic operation with assignment. They perform the operation and then assign the result to the variable.
+= (Addition Assignment)
Adds the right operand to the left operand and assigns the result to the left operand.
a += 3; // equivalent to a = a + 3
console.log(a); // outputs 8
-= (Subtraction Assignment)
Subtracts the right operand from the left operand and assigns the result to the left operand.
a -= 3; // equivalent to a = a - 3
console.log(a); // outputs 2
*= (Multiplication Assignment)
Multiplies the right operand with the left operand and assigns the result to the left operand.
a *= 3; // equivalent to a = a * 3
console.log(a); // outputs 15
/= (Division Assignment)
Divides the left operand by the right operand and assigns the result to the left operand.
a /= 2; // equivalent to a = a / 2
console.log(a); // outputs 5
%= (Remainder Assignment)
Calculates the remainder when the left operand is divided by the right operand and assigns the result to the left operand.
a %= 3; // equivalent to a = a % 3
console.log(a); // outputs 1
**= (Exponentiation Assignment)
Raises the left operand to the power of the right operand and assigns the result to the left operand.
a **= 3; // equivalent to a = a ** 3
console.log(a); // outputs 8
Bitwise Assignment Operators
Bitwise assignment operators perform bitwise operations on operands and then assign the result to the variable.
&= (Bitwise AND Assignment)
Performs a bitwise AND operation on the operands and assigns the result to the left operand.
a &= 3; // 0011 in binary, result is 0001
console.log(a); // outputs 1
|= (Bitwise OR Assignment)
Performs a bitwise OR operation on the operands and assigns the result to the left operand.
a |= 3; // 0011 in binary, result is 0111
console.log(a); // outputs 7
^= (Bitwise XOR Assignment)
Performs a bitwise XOR operation on the operands and assigns the result to the left operand.
a ^= 3; // 0011 in binary, result is 0110
console.log(a); // outputs 6
<<= (Left Shift Assignment)
Shifts the bits of the left operand to the left by the number of positions specified by the right operand and assigns the result to the left operand.
a <<= 1; // result is 1010
console.log(a); // outputs 10
>>= (Right Shift Assignment)
Shifts the bits of the left operand to the right by the number of positions specified by the right operand and assigns the result to the left operand.
a >>= 1; // result is 0010
console.log(a); // outputs 2
>>>= (Unsigned Right Shift Assignment)
Shifts the bits of the left operand to the right by the number of positions specified by the right operand, filling the leftmost bits with zeros, and assigns the result to the left operand.
a >>>= 1; // result is 0111...1101 (fills with zeros)
console.log(a); // outputs a large positive number due to unsigned shift
Logical Assignment Operators
Logical assignment operators combine logical operations with assignment.
&&= (Logical AND Assignment)
Assigns the right operand to the left operand if the left operand is truthy.
let b = false;
a &&= b; // equivalent to a = a && b
console.log(a); // outputs false
||= (Logical OR Assignment)
Assigns the right operand to the left operand if the left operand is falsy.
let b = true;
a ||= b; // equivalent to a = a || b
console.log(a); // outputs true
??= (Nullish Coalescing Assignment)
Assigns the right operand to the left operand if the left operand is null or undefined.
let b = 5;
a ??= b; // equivalent to a = a ?? b
console.log(a); // outputs 5
Practical Examples
Let's look at some practical examples that use multiple assignment operators together in common scenarios.
Example 1: Updating a Score
Consider a game where you need to update a player's score based on different events.
// Player scores a goal
score += 10; // Add 10 points
console.log(score); // outputs 10
// Player commits a foul
score -= 5; // Subtract 5 points
console.log(score); // outputs 5
// Player's score doubles
score *= 2; // Double the score
console.log(score); // outputs 10
Example 2: Managing Inventory
In an inventory management system, you might use assignment operators to update stock levels.
// New shipment arrives
stock += 50; // Add 50 units
console.log(stock); // outputs 150
// Sale of items
stock -= 20; // Subtract 20 units
console.log(stock); // outputs 130
// Items returned
stock += 10; // Add 10 units
console.log(stock); // outputs 140
Example 3: Configuring Settings
In a web application, you might configure settings with default values using logical assignment operators.
theme: 'dark',
language: 'en',
notifications: null
};
// User updates settings
config.theme ||= 'light'; // Keep current value since it's truthy
config.language ||= 'es'; // Update to 'es' if current value is falsy
config.notifications ??= true; // Update to true if current value is null or undefined
console.log(config); // outputs { theme: 'dark', language: 'en', notifications: true }
Practice Excercise Practice now
JavaScript String Operators
JavaScript provides several operators and methods to work with strings. Strings are sequences of characters used to represent text. In JavaScript, strings are immutable, meaning that once they are created, they cannot be altered directly. However, you can create new strings based on existing ones.
Basic String Operators
Concatenation Operator (+)
The concatenation operator + is used to combine two or more strings into a single string.
let name = "Alice";
let message = greeting + name; // "Hello, Alice"
console.log(message);
Concatenation Assignment Operator (+=)
The concatenation assignment operator += appends a string to an existing string variable.
message += "Bob"; // "Hello, Bob"
console.log(message);
String Methods
JavaScript provides various methods for string manipulation. Some of the most commonly used methods include length, charAt(), substring(), slice(), indexOf(), replace(), and template literals.
Length Property
The length property returns the number of characters in a string.
console.log(text.length); // 13
charAt()
The charAt() method returns the character at a specified index in a string.
console.log(text.charAt(0)); // "J"
console.log(text.charAt(4)); // "S"
substring()
The substring() method extracts a part of a string and returns it as a new string without modifying the original string.
let part = text.substring(0, 5); // "Hello"
console.log(part);
slice()
The slice() method extracts a section of a string and returns it as a new string. It can take negative indices, which count from the end of the string.
console.log(text.slice(0, 4)); // "Java"
console.log(text.slice(-6)); // "Script"
indexOf()
The indexOf() method returns the index of the first occurrence of a specified value in a string. If the value is not found, it returns -1.
console.log(text.indexOf("World")); // 7
console.log(text.indexOf("world")); // -1 (case-sensitive)
replace()
The replace() method searches for a specified value in a string and replaces it with another value.
let newText = text.replace("World", "JavaScript"); // "Hello, JavaScript!"
console.log(newText);
Template Literals
Template literals, introduced in ES6, allow for easier string interpolation and multi-line strings. Template literals are enclosed by backticks (`) instead of single or double quotes.
String Interpolation
String interpolation allows you to embed expressions within a string using ${expression} syntax.
let age = 25;
let message = `My name is ${name} and I am ${age} years old.`;
console.log(message); // "My name is Alice and I am 25 years old."
Multi-line Strings
Template literals make it easy to create multi-line strings.
multi-line
string.`;
console.log(multiLine);
Practice Excercise Practice now
Adding Strings And Numbers
In JavaScript, you can add both strings and numbers, but the results differ based on the types involved. This guide will explain how adding strings and numbers works in JavaScript, along with examples.
Adding Numbers
When you add two numbers in JavaScript using the + operator, JavaScript performs addition:
let num2 = 3;
let sum = num1 + num2;
console.log(sum); // Outputs: 8
Here, num1 and num2 are both numeric values, so adding them gives the expected sum of 8.
Adding Strings
When you add two strings or a string and another value (like a number), JavaScript concatenates them into a new string:
let str2 = ' World';
let greeting = str1 + str2;
console.log(greeting); // Outputs: Hello World
In this example, str1 and str2 are concatenated using the + operator to form the string 'Hello World'.
Mixing Numbers and Strings
JavaScript allows you to mix numbers and strings in an addition operation. When you do this, JavaScript converts the numbers to strings and concatenates them with the other string(s):
let string = ' apples';
let result = number + string;
console.log(result); // Outputs: '5 apples'
Here, the number 5 is converted to the string '5', and then it is concatenated with the string ' apples', resulting in '5 apples'.
Automatic Type Conversion (Type Coercion)
JavaScript is a weakly typed language, which means it can automatically convert one data type to another as needed. This is known as type coercion. When you use the + operator with different types, JavaScript converts one of the operands to match the other:
Number to String Conversion
let bananas = ' bananas';
let result = apples + bananas;
console.log(result); // Outputs: '5 bananas'
In this example, the number 5 is converted to the string '5' and then concatenated with the string ' bananas', resulting in '5 bananas'.
String to Number Conversion
let sum = 5 + num;
console.log(sum); // Outputs: 15 (the string '10' is converted to the number 10)
In this example, the string '10' is converted to the number 10, and then added to 5, resulting in 15.
Examples of Adding Strings and Numbers
Example 1: Adding Numbers
let num2 = 5;
let sum = num1 + num2;
console.log(sum); // Outputs: 15
Example 2: Adding Strings
let str2 = ' World';
let greeting = str1 + str2;
console.log(greeting); // Outputs: Hello World
Example 3: Mixing Numbers and Strings
let oranges = ' oranges';
let result = 'I have ' + apples + oranges;
console.log(result); // Outputs: I have 5 oranges
In this example, the number 5 is converted to the string '5' and concatenated with 'I have ' and ' oranges'.
Practice Excercise Practice now
JavaScript Comparison Operators
JavaScript provides several comparison operators that allow you to compare values. These operators return a boolean (true or false) based on whether the comparison is true or false. This guide will cover the most commonly used comparison operators along with examples.
1. Equal to (==)
The equality operator (==) compares two values for equality, after converting both values to a common type.
Example:
let num2 = '5';
console.log(num1 == num2); // Outputs: true
In this example, even though num1 is a number and num2 is a string, JavaScript converts num1 to a string before comparing them, resulting in true.
2. Not equal to (!=)
The inequality operator (!=) compares two values for inequality, after converting both values to a common type.
Example:
let num2 = '5';
console.log(num1 != num2); // Outputs: false
Here, num1 is equal to num2 in value, so the inequality comparison returns false.
3. Strict equal to (===)
The strict equality operator (===) compares two values for equality, but without type conversion.
Example:
let num2 = '5';
console.log(num1 === num2); // Outputs: false
In this case, num1 is a number and num2 is a string, so they are not strictly equal.
4. Strict not equal to (!==)
The strict inequality operator (!==) compares two values for inequality, without type conversion.
Example:
let num2 = '5';
console.log(num1 !== num2); // Outputs: true
Here, num1 is a number and num2 is a string, so they are not strictly equal, resulting in true.
5. Greater than (>)
The greater than operator (>) compares whether the left operand is greater than the right operand.
Example:
let num2 = 5;
console.log(num1 > num2); // Outputs: true
In this example, num1 is greater than num2, so the comparison returns true.
6. Less than (<)
The less than operator (<) compares whether the left operand is less than the right operand.
Example:
let num2 = 10;
console.log(num1 < num2); // Outputs: true
Here, num1 is less than num2, so the comparison returns true.
7. Greater than or equal to (>=)
The greater than or equal to operator (>=) compares whether the left operand is greater than or equal to the right operand.
Example:
let num2 = 10;
console.log(num1 >= num2); // Outputs: true
In this case, num1 is equal to num2, so the comparison returns true.
8. Less than or equal to (<=)
The less than or equal to operator (<=) compares whether the left operand is less than or equal to the right operand.
Example:
let num2 = 10;
console.log(num1 <= num2); // Outputs: true
Here, num1 is less than num2, so the comparison returns true.
Examples of Using Comparison Operators
Example 1: Using Equal to (==)
let num2 = '5';
console.log(num1 == num2); // Outputs: true
Example 2: Using Not equal to (!=)
let num2 = '5';
console.log(num1 != num2); // Outputs: false
Example 3: Using Strict equal to (===)
let num1 = 5;
let num2 = '5';
console.log(num1 === num2); // Outputs: false
Example 4: Using Greater than (>)
let num2 = 5;
console.log(num1 > num2); // Outputs: true
Example 5: Using Less than (<)
let num2 = 10;
console.log(num1 < num2); // Outputs: true
Example 6: Using Greater than or equal to (>=)
let num2 = 10;
console.log(num1 >= num2); // Outputs: true
Example 7: Using Less than or equal to (<=)
let num2 = 10;
console.log(num1 <= num2); // Outputs: true
JavaScript comparison operators are fundamental for comparing values and controlling the flow of your programs. They allow you to make decisions based on whether values are equal, not equal, greater than, less than, or other comparisons.
Practice Excercise Practice now
JavaScript Logical Operators
JavaScript logical operators are used to combine or invert boolean values. These operators are crucial in controlling the flow of your program based on multiple conditions. The primary logical operators in JavaScript are && (logical AND), || (logical OR), and ! (logical NOT). This guide will cover each of these operators with examples to illustrate their use.
1. Logical AND (&&)
The logical AND operator (&&) returns true if both operands are true. If either operand is false, the operator returns false. This operator is often used in conditional statements to ensure that multiple conditions are true before executing a block of code.
Syntax:
Example:
let b = false;
let c = true;
console.log(a && b); // Outputs: false
console.log(a && c); // Outputs: true
if (a && c) {
console.log("Both conditions are true.");
} else {
console.log("At least one condition is false.");
}
In this example, a && b evaluates to false because b is false, while a && c evaluates to true because both a and c are true.
2. Logical OR (||)
The logical OR operator (||) returns true if at least one of the operands is true. If both operands are false, the operator returns false. This operator is useful when you need to check if at least one condition is true.
Syntax:
let b = false;
let c = false;
console.log(a || b); // Outputs: true
console.log(b || c); // Outputs: false
if (a || b) {
console.log("At least one condition is true.");
} else {
console.log("Both conditions are false.");
}
In this example, a || b evaluates to true because a is true, while b || c evaluates to false because both b and c are false.
3. Logical NOT (!)
The logical NOT operator (!) inverts the value of a boolean. If the operand is true, it returns false, and if the operand is false, it returns true. This operator is useful for toggling the boolean state or for checking if a condition is not true.
Example:
let b = false;
console.log(!a); // Outputs: false
console.log(!b); // Outputs: true
if (!b) {
console.log("Condition is false.");
} else {
console.log("Condition is true.");
}
In this example, !a evaluates to false because a is true, while !b evaluates to true because b is false.
Combining Logical Operators
Logical operators can be combined to form complex conditions. The order of evaluation follows standard operator precedence, where ! is evaluated first, followed by &&, and then ||. Parentheses can be used to control the order of evaluation explicitly.
Example:
let b = false;
let c = true;
console.log((a && b) || c); // Outputs: true
console.log(a && (b || c)); // Outputs: true
if ((a && b) || c) {
console.log("Complex condition is true.");
} else {
console.log("Complex condition is false.");
}
In this example, (a && b) || c evaluates to true because a && b is false, but c is true, resulting in true due to the OR operator. Similarly, a && (b || c) evaluates to true because b || c is true and a is also true.
Short-Circuit Evaluation
JavaScript logical operators use short-circuit evaluation, meaning they stop evaluating as soon as the result is determined. This can be useful for optimizing performance or avoiding errors.
Example:
let b = true;
function checkB() {
console.log("Checking b...");
return b;
}
console.log(a && checkB()); // Outputs: false
console.log(a || checkB()); // Outputs: true and "Checking b..."
if (a && checkB()) {
console.log("Both conditions are true.");
} else {
console.log("At least one condition is false.");
}
In this example, a && checkB() evaluates to false without calling checkB() because a is false. On the other hand, a || checkB() evaluates checkB() because a is false, resulting in true and logging "Checking b...".
Practical Examples
Example 1: User Authentication
Checking if a user is logged in and has the required permissions.
let hasPermission = false;
if (isLoggedIn && hasPermission) {
console.log("Access granted.");
} else {
console.log("Access denied.");
}
Example 2: Default Values
Providing default values for function parameters.
javascript
Copy code
function greet(name) {
let greeting = name || "Guest";
console.log("Hello, " + greeting + "!");
}
greet("Alice"); // Outputs: Hello, Alice!
greet(); // Outputs: Hello, Guest!
Example 3: Toggling a Feature
Enabling or disabling a feature based on a condition.
isFeatureEnabled = !isFeatureEnabled;
console.log("Feature enabled: " + isFeatureEnabled); // Outputs: Feature enabled: true
isFeatureEnabled = !isFeatureEnabled;
console.log("Feature enabled: " + isFeatureEnabled); // Outputs: Feature enabled: false
JavaScript logical operators are essential tools for controlling the flow of your code based on multiple conditions. The &&
(logical AND), ||
(logical OR), and !
(logical NOT) operators allow you to create complex logical expressions and make decisions based on boolean logic.
Practice Excercise Practice now
JavaScript Type Operators
JavaScript is a dynamically typed language, which means that variables can hold values of any type without type constraints. Understanding the type of data you are working with is crucial for debugging and writing effective code. JavaScript provides type operators to determine and convert the types of variables. The key type operators in JavaScript include typeof, instanceof, and various methods for type conversion.
1. typeof Operator
The typeof operator returns a string indicating the type of the unevaluated operand. This operator is useful for determining the type of a variable or expression.
Example:
let b = 'Hello';
let c = true;
let d;
let e = null;
let f = { name: 'John' };
console.log(typeof a); // Outputs: "number"
console.log(typeof b); // Outputs: "string"
console.log(typeof c); // Outputs: "boolean"
console.log(typeof d); // Outputs: "undefined"
console.log(typeof e); // Outputs: "object" (this is a historical bug in JavaScript)
console.log(typeof f); // Outputs: "object"
2. instanceof Operator
The instanceof operator tests whether an object is an instance of a specific constructor or class. This operator returns true if the object is an instance of the specified constructor, and false otherwise.
Example:
this.name = name;
}
let john = new Person('John');
let notAnObject = 'Hello';
console.log(john instanceof Person); // Outputs: true
console.log(notAnObject instanceof Person); // Outputs: false
3. Type Conversion
JavaScript provides methods to convert values from one type to another, including String(), Number(), and Boolean().
String Conversion
To convert a value to a string, you can use the String() function or the toString() method.
Example:
let num = 123;
let bool = true;
let strNum = String(num);
let strBool = bool.toString();
console.log(strNum); // Outputs: "123"
console.log(typeof strNum); // Outputs: "string"
console.log(strBool); // Outputs: "true"
console.log(typeof strBool); // Outputs: "string"
Number Conversion
To convert a value to a number, you can use the Number() function or parse the value using parseInt() or parseFloat().
Example:
let floatStr = '123.45';
let bool = true;
let num = Number(str);
let floatNum = parseFloat(floatStr);
let boolNum = Number(bool);
console.log(num); // Outputs: 123
console.log(typeof num); // Outputs: "number"
console.log(floatNum); // Outputs: 123.45
console.log(typeof floatNum); // Outputs: "number"
console.log(boolNum); // Outputs: 1
console.log(typeof boolNum); // Outputs: "number"
Boolean Conversion
To convert a value to a boolean, you can use the Boolean() function.
Example:
let emptyStr = '';
let num = 0;
let nonZeroNum = 42;
let boolStr = Boolean(str);
let boolEmptyStr = Boolean(emptyStr);
let boolNum = Boolean(num);
let boolNonZeroNum = Boolean(nonZeroNum);
console.log(boolStr); // Outputs: true
console.log(boolEmptyStr); // Outputs: false
console.log(boolNum); // Outputs: false
console.log(boolNonZeroNum); // Outputs: true
Practical Examples
Example 1: Checking Types in Function
You can use the typeof operator to ensure the correct types are passed to a function.
function add(a, b) {
if (typeof a !== 'number' || typeof b !== 'number') {
throw new Error('Both arguments must be numbers');
}
return a + b;
}
try {
console.log(add(2, 3)); // Outputs: 5
console.log(add('2', 3)); // Throws an error
} catch (e) {
console.error(e.message);
}
Example 2: Using instanceof with Custom Objects
The instanceof operator can verify the instance of a custom object.
constructor(name) {
this.name = name;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
}
let myDog = new Dog('Buddy', 'Golden Retriever');
console.log(myDog instanceof Dog); // Outputs: true
console.log(myDog instanceof Animal); // Outputs: true
console.log(myDog instanceof Object); // Outputs: true
console.log(myDog instanceof Array); // Outputs: false
Example 3: Type Conversion in Conditional Statements
Type conversion can be particularly useful in conditional statements.
if (Number(value)) {
console.log('The value is a number');
} else {
console.log('The value is not a number');
}
let emptyValue = '';
if (Boolean(emptyValue)) {
console.log('The value is truthy');
} else {
console.log('The value is falsy');
}
JavaScript type operators and conversion functions are essential tools for handling different data types dynamically. The typeof
operator helps determine the type of a variable, while the instanceof
operator checks the instance relationship of an object. Type conversion functions such as String()
, Number()
, and Boolean()
allow you to convert values from one type to another, facilitating more robust and flexible code.
Practice Excercise Practice now
JavaScript Bitwise Operators
JavaScript bitwise operators are used to perform bitwise operations on integers. These operations treat their operands as a sequence of 32 bits (zeros and ones) rather than as decimal, hexadecimal, or octal numbers. This can be particularly useful for certain low-level operations, such as encoding and decoding information, manipulating bits in a bit field, or performing certain arithmetic operations more efficiently.
Types of Bitwise Operators
JavaScript supports the following bitwise operators:
Bitwise AND (&):
The bitwise AND operator (&) compares each bit of its first operand to the corresponding bit of its second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the result bit is set to 0.
Example:
console.log(result); // Output: 1
Bitwise OR (|):
The bitwise OR operator (|) compares each bit of its first operand to the corresponding bit of its second operand. If either bit is 1, the corresponding result bit is set to 1. If both bits are 0, the result bit is set to 0.
console.log(result); // Output: 7
Bitwise XOR (^):
The bitwise XOR operator (^) compares each bit of its first operand to the corresponding bit of its second operand. If the bits are different, the corresponding result bit is set to 1. If the bits are the same, the result bit is set to 0.
Example:
console.log(result); // Output: 6
Bitwise NOT (~):
The bitwise NOT operator (~) inverts all the bits of its operand. This can be useful for reversing the bits in a value.
let result = ~num; // ~00000000000000000000000000000101 = 11111111111111111111111111111010 (-6 in decimal)
console.log(result); // Output: -6
Left Shift (<<):
The left shift operator (<<) moves the bits of its first operand to the left by the number of positions specified by the second operand. Excess bits shifted off to the left are discarded, and empty positions are set to 0.
Example:
console.log(result); // Output: 10
Sign-propagating Right Shift (>>):
The sign-propagating right shift operator (>>) moves the bits of its first operand to the right by the number of positions specified by the second operand. Bits that are shifted off to the right are discarded. The leftmost bits are filled with the sign bit (0 for positive
numbers, 1 for negative numbers).
Example:
console.log(result); // Output: 2
Zero-fill Right Shift (>>>):
The zero-fill right shift operator (>>>) moves the bits of its first operand to the right by the number of positions specified by the second operand. Bits that are shifted off to the right are discarded. The leftmost bits are filled with 0.
Example:
console.log(result); // Output: 2
Practical Examples
Example 1: Checking Bitwise AND Operation
let b = 3; // 0011 in binary
let result = a & b; // 0101 & 0011 = 0001 (1 in decimal)
console.log(result); // Output: 1
Example 2: Performing Bitwise XOR Operation
let b = 3; // 0011 in binary
let result = a ^ b; // 0101 ^ 0011 = 0110 (6 in decimal)
console.log(result); // Output: 6
Example 3: Using Bitwise Left Shift Operator
let result = a << 1; // 0101 << 1 = 1010 (10 in decimal)
console.log(result); // Output: 10
Use Cases
- Data Compression: Bitwise operators can be used to compress data by manipulating bits directly.
- Image Processing: Operations such as cropping, flipping, or rotating images can be done using bitwise operators.
- Networking: Bitwise operators can be used to implement network protocols and data transmission.
- Cryptography: Bitwise operations are fundamental in encryption and decryption algorithms.
Practice Excercise Practice now
Products
Partner
Copyright © RVR Innovations LLP 2024 | All rights reserved - Mytat.co is the venture of RVR Innovations LLP