Topic Covered In This section:
In JavaScript, there are several ways to display output. Below are the most common methods along with explanations:
This method outputs messages to the web console. It’s mainly used for debugging purposes.
Example:
console.log("Hello, world!"); // Displays "Hello, world!" in the console
This method creates a pop-up alert box that displays a message to the user. It halts the execution of code until the user dismisses the alert.
Example:
alert("This is an alert message!"); // Displays a pop-up alert
This method writes directly to the HTML document. It can overwrite the entire content of the document if used after the page has loaded.
Example:
document.write("Hello, document!"); // Writes "Hello, document!" to the page
You can use the innerHTML property to insert content into an HTML element on the page. This is a common way to dynamically update content.
Example:
document.getElementById("output").innerHTML = "Hello, world!";
This method displays a dialog box that prompts the user for input and returns that input as a string.
Example:
let userInput = prompt("Please enter your name:");
console.log("You entered: " + userInput); // Displays the user's input in the console
Variables in JavaScript are like containers that store data values. They allow you to name and hold information that you can use and manipulate throughout your code. You can think of a variable as a label for a value, which makes it easier to work with. In JavaScript, there are three main ways to declare variables: var, let, and const.
This is the old way of declaring variables. It has a function scope, which means it is available throughout the function in which it is defined.
Example:
var name = "Jala Academy";
console.log(name); // Output: Jala Academy
Introduced in ES6 (ECMAScript 2015), let allows you to declare variables that can be changed later. It has a block scope, which means it is only available within the block of code (like inside a loop or an if statement).
Example:
let age = 25;
age = 26; // You can change the value
console.log(age); // Output: 26
const pi = 3.14;
console.log(pi); // Output: 3.14
// pi = 3.14159;
// This will cause an error because you can't reassign a const variable.
Variables can store different types of data, including Primitive data types and Reference data types.
A data type that holds a single, simple value directly in memory, such as a String, Number,Boolean ,Null ,Undefined ,Symbol ,BigInt . Each primitive value is independent, so changes to one do not affect others.
let name = "Talha";
let greeting = 'Hello, world!';
let templateLiteral = `Hello, ${name}!`; // Using template literals
let age = 25; // Integer
let price = 19.99; // Float
let isStudent = true;
let hasLicense = false;
let x; // x is declared but not defined
console.log(x); // Output: undefined
let y = null; // y is explicitly set to null
const sym = Symbol('description'); // Creating a symbol
// Creating BigInt using the 'n' suffix
let bigInt1 = 123456789012345678901234567890n;
console.log(bigInt1); // Output: 123456789012345678901234567890n
// Creating BigInt using the BigInt() constructor
let bigInt2 = BigInt(123456789012345678901234567890);
console.log(bigInt2); // Output: 123456789012345678901234567890n
These are more complex data types that store collections or objects. Instead of storing the actual value, they store a reference (or address) to where the data is located in memory, allowing the original data to be modified. Examples include Object, Array, and Function.
let person = {
name: "Talha",
age: 25,
isStudent: true
};
let fruits = ["apple", "banana", "orange"]; // Array of strings
let numbers = [1, 2, 3, 4, 5]; // Array of numbers
function greet(name) {
return `Hello, ${name}!`;
}
let greetingMessage = greet("Talha"); // Calls the function
JavaScript operators are special symbols used in scripts to perform operations on operands, such as arithmetic calculations, logical comparisons, or value assignments. It plays a crucial role in controlling the flow and processing of data within the language. The operators are Arithmetic Operators, Assignment Operators, Comparison Operators and Logical Operators
These operators are used to perform basic mathematical operations.
let a = 10;
let b = 5;
console.log("Addition:", a + b); // 10 + 5 = 15
console.log("Subtraction:", a - b); // 10 - 5 = 5
console.log("Multiplication:", a * b); // 10 * 5 = 50
console.log("Division:", a / b); // 10 / 5 = 2
console.log("Modulus:", a % b); // 10 % 5 = 0 (remainder of 10 divided by 5)
These operators are used to assign values to variables.
let x = 10; // Assignment: assigns 10 to x
x += 5; // Addition assignment: x = x + 5 (x is now 15)
x -= 3; // Subtraction assignment: x = x - 3 (x is now 12)
x *= 2; // Multiplication assignment: x = x * 2 (x is now 24)
x /= 4; // Division assignment: x = x / 4 (x is now 6)
x %= 5; // Modulus assignment: x = x % 5 (x is now 1)
x **= 3; // Exponentiation assignment: x = x ** 3 (x is now 1)
These operators compare two values and return true or false.
let a = 5;
let b = 10;
console.log(a == b); // Equal to: false (5 is not equal to 10)
console.log(a === 5); // Strict equal to: true (5 is equal to 5, and type matches)
console.log(a != b); // Not equal to: true (5 is not equal to 10)
console.log(a !== b); // Strict not equal to: true (5 is not equal to 10, and type matches)
console.log(a < b); // Less than: true (5 is less than 10)
console.log(a > b); // Greater than: false (5 is not greater than 10)
console.log(a <= 5); // Less than or equal to: true (5 is equal to 5)
console.log(b >= 10); // Greater than or equal to: true (10 is equal to 10)
These operators are used to combine multiple conditions.
let isRaining = true;
let isWarm = false;
console.log(isRaining && isWarm); // Logical AND: false (both conditions are not true)
console.log(isRaining || isWarm); // Logical OR: true (at least one condition is true)
console.log(!isRaining); // Logical NOT: false (reverses true to false)
In JavaScript, type conversion refers to the process of converting one data type into another. Coercion, on the other hand, is the automatic conversion that occurs when performing operations between different types. Here’s a breakdown of both concepts with examples:
You can convert between types using built-in functions:
// Convert Number to String
let num = 42;
let strNum = String(num); // "42"
console.log(typeof strNum); // "string"
// Convert String to Number
let str = "100";
let numStr = Number(str); // 100
console.log(typeof numStr); // "number"
// Convert other types to Boolean
let truthyValue = Boolean(1); // true (non-zero numbers are truthy)
let falsyValue = Boolean(0); // false (0 is falsy)
console.log(truthyValue); // true
console.log(falsyValue); // false
Coercion is the automatic conversion that happens in certain situations, especially in operations involving mixed types.
// Number + String (Coercion happens here)
let result = 5 + "5"; // "55" (5 is coerced to a string)
console.log(result); // "55"
// String - Number (Coercion)
let subtraction = "10" - 5; // 5 (string "10" is coerced to a number)
console.log(subtraction); // 5
// Comparing different types (loose equality)
console.log(5 == "5"); // true (coerced to the same type before comparison)
console.log(5 === "5"); // false (strict equality, no coercion)