JavaScript Fundamentals

Dive deep into the world of JavaScript, learn its core concepts, and become a proficient web developer with our comprehensive guide.

Start Learning

Introduction to JavaScript

JavaScript is a versatile, high-level programming language primarily used for creating interactive and dynamic web pages. Originally developed by Brendan Eich in 1995 while working at Netscape Communications, JavaScript quickly became a fundamental technology for web development.

Historical Background

In the mid-1990s, Netscape Navigator was the dominant web browser, and there was a need for a lightweight, browser-based scripting language. Brendan Eich was tasked with creating a language that could be easily used by web developers to add interactivity to websites. In just 10 days, he developed the initial version of JavaScript, which was originally named "Mocha" and later renamed to "LiveScript" before finally becoming "JavaScript".

Key Characteristics

// Basic JavaScript example demonstrating its interpretive nature
console.log("Hello, JavaScript!");

function greetUser(name) {
    return `Welcome, ${name}!`;
}

// This code is interpreted and executed directly by the browser
alert(greetUser("Developer"));

Standardization

After its creation at Netscape, JavaScript was submitted to ECMA International for standardization. This led to the ECMAScript specification, with JavaScript being the most well-known implementation. The language has undergone several versions, with ES6 (ECMAScript 2015) introducing significant improvements and modern features.

Understanding Variables

Variables are containers for storing data values. In JavaScript, you can declare variables using three keywords:

// var: Function or globally scoped
var age = 25;

// let: Block-scoped, can be updated
let name = "John";

// const: Block-scoped, cannot be reassigned
const PI = 3.14159;

Variable Naming Rules

JavaScript has specific rules for naming variables:

Correct Variable Names:

// Valid variable names
let name = "John";
let age123 = 25;
let _privateVar = "secret";
let $specialVar = "special";
let firstName = "John";
let user_name = "jane";

Incorrect Variable Names:

// Invalid variable names
let 123name = "John";  // Cannot start with a number
let first-name = "John";  // Cannot use hyphens
let class = "JavaScript";  // Cannot use reserved keywords
let #specialVar = "test";  // Cannot use special characters except $ and _

Variable Naming Rules:

Variable Practice Exercises

Identify Correct and Incorrect Variable Names

Determine if the following variable names are correct or incorrect:

  1. user_name
  2. 123username
  3. firstName
  4. first-name
  5. $price
  6. _hidden

Variable Quiz

Test Your Knowledge

  1. What is the difference between 'let' and 'const'?
  2. Can you start a variable name with a number?
  3. What naming convention is recommended in JavaScript?
  4. How many ways can you declare a variable in JavaScript?

JavaScript Keywords

Keywords are reserved words in JavaScript that have special meanings and cannot be used as variable names, function names, or identifiers.

// Examples of using keywords
let name = "John";  // 'let' is a keyword for variable declaration
const PI = 3.14159;  // 'const' is a keyword for constant declaration
if (age >= 18) {  // 'if' is a control flow keyword
  console.log("You are an adult");
}
function greet() {  // 'function' is a keyword for defining functions
  return "Hello!";
}

Common JavaScript Keywords

Important Notes about Keywords

  • Keywords cannot be used as variable or function names
  • They have predefined meanings in the JavaScript language
  • Using a keyword incorrectly will result in a syntax error

JavaScript Operators

Operators are special symbols used to perform operations on variables and values. JavaScript supports several types of operators.

Arithmetic Operators

Operator Description Example
+ Addition let sum = 5 + 3; // sum is 8
- Subtraction let diff = 10 - 4; // diff is 6
* Multiplication let product = 5 * 3; // product is 15
/ Division let quotient = 15 / 3; // quotient is 5
% Modulus (Remainder) let remainder = 17 % 5; // remainder is 2
** Exponentiation let power = 2 ** 3; // power is 8
++ Increment let x = 5; x++; // x is now 6
-- Decrement let y = 5; y--; // y is now 4
// Practical example of arithmetic operators
let a = 10;
let b = 3;

console.log(a + b);  // Addition: 13
console.log(a - b);  // Subtraction: 7
console.log(a * b);  // Multiplication: 30
console.log(a / b);  // Division: 3.333
console.log(a % b);  // Modulus: 1
console.log(a ** b); // Exponentiation: 1000

Understanding Arithmetic Operators

  • Arithmetic operators work with numeric values
  • The + operator can also concatenate strings
  • Increment (++) and decrement (--) can be used as prefix or postfix

Assignment Operators in JavaScript

Assignment operators allow you to assign values to variables and perform operations simultaneously. They provide a concise way to modify variable values.

Operator Description Example Equivalent To
= Basic Assignment let x = 5; x = 5
+= Addition Assignment x += 3; x = x + 3;
-= Subtraction Assignment x -= 3; x = x - 3;
*= Multiplication Assignment x *= 3; x = x * 3;
/= Division Assignment x /= 3; x = x / 3;
%= Modulus Assignment x %= 3; x = x % 3;
**= Exponentiation Assignment x **= 3; x = x ** 3;
// Assignment Operator Examples
let x = 10;

// Basic assignment
x = 20;  // x is now 20

// Compound assignment operators
x += 5;  // Equivalent to x = x + 5, x is now 25
x -= 3;  // Equivalent to x = x - 3, x is now 22
x *= 2;  // Equivalent to x = x * 2, x is now 44
x /= 4;  // Equivalent to x = x / 4, x is now 11
x %= 3;  // Equivalent to x = x % 3, x is now 2

// Practical example in a real-world scenario
let score = 100;
let penalty = 20;

score -= penalty;  // Deduct penalty from score
console.log(score);  // 80

Key Insights about Assignment Operators

  • Compound assignment operators provide a more concise way to modify variables
  • They combine an arithmetic operation with assignment in a single step
  • They can make code more readable and reduce redundancy
  • They work with all basic arithmetic operations

Relational and Logical Operators

Relational and logical operators are essential for comparing values and creating conditional logic in JavaScript.

Relational Operators

Operator Description Example Result
== Equal to (loose comparison) 5 == "5" true
=== Strict equal to (checks value and type) 5 === "5" false
!= Not equal to (loose comparison) 5 != "6" true
> Greater than 10 > 5 true
< Less than 5 < 10 true
>= Greater than or equal to 10 >= 10 true
<= Less than or equal to 5 <= 5 true

Logical Operators

Operator Description Example Result
&& Logical AND true && false false
|| Logical OR true || false true
! Logical NOT !true false
// Relational Operators Examples
let x = 10;
let y = 5;

console.log(x > y);     // true
console.log(x == "10"); // true (loose comparison)
console.log(x === 10);  // true
console.log(x !== "10"); // true

// Logical Operators Examples
let isAdult = true;
let hasLicense = false;

console.log(isAdult && hasLicense);  // false
console.log(isAdult || hasLicense);  // true
console.log(!isAdult);               // false

Key Insights

  • Use === for strict equality comparison
  • Logical AND (&&) requires all conditions to be true
  • Logical OR (||) requires at least one condition to be true
  • Logical NOT (!) reverses the boolean value

Conditional (Ternary) Operator in JavaScript

The conditional operator, also known as the ternary operator, is a compact way to write conditional statements in a single line.

// Syntax of Conditional Operator
condition ? expressionIfTrue : expressionIfFalse;

Basic Structure and Usage

Component Description Example
Condition A boolean expression that is evaluated age >= 18
Expression If True Value or expression returned if condition is true "Adult"
Expression If False Value or expression returned if condition is false "Minor"
// Simple Conditional Operator Examples
let age = 20;

// Basic usage
let status = age >= 18 ? "Adult" : "Minor";
console.log(status);  // "Adult"

// More complex example
let canVote = age >= 18 ? true : false;
console.log(canVote);  // true

// Nested conditional operator
let message = age < 13 ? "Child" 
          : age < 20 ? "Teenager" 
          : "Adult";
console.log(message);  // "Adult"

// Using with functions or expressions
function checkDiscount(age) {
  return age >= 65 ? 0.2 : 
         age >= 18 ? 0.1 : 0;
}

let discount = checkDiscount(70);
console.log(discount);  // 0.2 (20% senior discount)

Practical Use Cases

// Real-world examples
let username = "";
let displayName = username ? username : "Anonymous";
console.log(displayName);  // "Anonymous"

// Simple conditional rendering in React-like logic
let isLoggedIn = true;
let greeting = isLoggedIn 
  ? `Welcome back, ${username}!`
  : "Please log in";
console.log(greeting);  // "Please log in"

// Conditional assignment
let score = 85;
let grade = score >= 90 ? "A" 
        : score >= 80 ? "B"
        : score >= 70 ? "C"
        : score >= 60 ? "D"
        : "F";
console.log(grade);  // "B"

Key Insights about Conditional Operator

  • Provides a shorthand way to write simple if-else statements
  • Can be nested, but excessive nesting can reduce readability
  • Useful for quick, simple conditional assignments
  • Can return any type of value (strings, numbers, booleans, etc.)

Practice Exercises

  1. Write a ternary operator to check if a number is even or odd
  2. Create a ternary operator that returns a discount rate based on a customer's total purchase
  3. Use a nested ternary operator to categorize a temperature reading

JavaScript Data Types

JavaScript has two main categories of data types: Primitive and Reference types. Understanding these types is crucial for effective programming.

Primitive Data Types

Type Description Example Typeof Result
Number Represents numeric values 42, 3.14, -10 "number"
String Textual data "Hello", 'JavaScript' "string"
Boolean Logical entity true, false "boolean"
// Primitive Data Types Examples
// Number
let age = 25;
let price = 19.99;

// String
let name = "John Doe";
let greeting = 'Hello, World!';

// Boolean
let isStudent = true;
let hasLicense = false;


// Typeof demonstration
console.log(typeof age);          // "number"
console.log(typeof name);          // "string"
console.log(typeof isStudent);     // "boolean"

JavaScript Write and WriteLn Methods

JavaScript provides methods to write output to the document or browser window.

// document.write() method
document.write("Hello, World!");  // Writes directly to the HTML document

// document.writeln() method
document.writeln("This is a line of text");  // Writes a line with an automatic line break

Important Considerations

Best Practices

  • Avoid using document.write() in production websites
  • Prefer modern methods like innerHTML, textContent, or DOM manipulation

JavaScript Comments

Comments are used to explain code and make it more readable. JavaScript supports two types of comments:

// Single-line comment
// This is a single-line comment explaining the code

/* Multi-line comment
This comment can span
multiple lines */

// Example with actual code
let x = 5;  // Declaring a variable
/* 
Complex calculation
Multiplying x by 2 
*/
let result = x * 2;

Comment Types

Comment Best Practices

  • Use comments to explain complex logic
  • Keep comments concise and meaningful
  • Update comments when code changes

JavaScript Conditional Statements

Conditional statements are used to perform different actions based on different conditions. They allow your code to make decisions and execute different code blocks based on those decisions.

Types of Conditional Statements

// Basic structure of conditional statements
if (condition) {
    // code to be executed if condition is true
}

If Statement

The if statement is the most basic type of conditional statement. It executes a block of code if a specified condition is true.

// Simple if statement
let age = 18;

if (age >= 18) {
    console.log("You are eligible to vote!");
}

// If statement with multiple conditions
let score = 85;
let attendance = 90;

if (score >= 80 && attendance >= 85) {
    console.log("You qualify for honors!");
}

Questions

  • Write a program that checks if a number is positive and prints "The number is positive."
  • Create a program that checks if a number is greater than 100 and prints "Large number!" if it is.

If...Else Statement

The if...else statement allows you to execute one block of code if the condition is true and another if it's false.

// Basic if...else structure
let age = 15;

if (age >= 18) {
    console.log("You can vote!");
} else {
    console.log("You are too young to vote.");
}

// Practical example
let onlineStatus = true;

if (onlineStatus) {
    console.log("User is online");
} else {
    console.log("User is offline");
}

When to Use If...Else

  • Write a program to check if a number is positive or negative.Print "Positive number" or "Negative number" accordingly.
  • Create a program to check if a person’s age is 18 or older. If true, print "Eligible to vote"; otherwise, print "Not eligible to vote." "
  • Create a program to check if a number is even or odd. Print "Even number" or "Odd number" accordingly.
  • Write a program to check if the temperature is above 25. If true, print "It's warm"; otherwise, print "It's cold.

Else If Statement

The else if statement allows you to test multiple conditions in sequence.

// Multiple conditions with else if
let score = 85;

if (score >= 90) {
    console.log("Grade: A");
} else if (score >= 80) {
    console.log("Grade: B");
} else if (score >= 70) {
    console.log("Grade: C");
} else {
    console.log("Grade: F");
}

// Practical example
let time = 14;

if (time < 12) {
    console.log("Good morning!");
} else if (time < 18) {
    console.log("Good afternoon!");
} else {
    console.log("Good evening!");
}

Best Practices

  • Write a program to simulate a traffic light system:
    If the light is "Red", print "Stop".
    If the light is "Yellow", print "Get Ready".
    If the light is "Green", print "Go".
    For any other input, print "Invalid input"

Nested If Statements

Nested if statements are if statements inside other if statements, allowing for more complex condition testing.

// Nested if statement example
let age = 25;
let hasLicense = true;

if (age >= 18) {
    if (hasLicense) {
        console.log("You can drive a car");
    } else {
        console.log("You need to get a license first");
    }
} else {
    console.log("You are too young to drive");
}

// Complex nested example
let username = "admin";
let password = "12345";
let isActive = true;

if (username === "admin") {
    if (password === "12345") {
        if (isActive) {
            console.log("Login successful");
        } else {
            console.log("Account is inactive");
        }
    } else {
        console.log("Incorrect password");
    }
} else {
    console.log("Invalid username");
}

Important Considerations

  • Avoid deeply nested if statements (more than 3 levels) for better readability
  • Consider using logical operators (&&, ||) instead of nesting when possible
  • Use proper indentation to maintain code clarity

Complex Logical Conditions

In JavaScript, you can combine multiple conditions using logical operators (AND &&, OR ||) to create complex conditional statements. Understanding how to combine these operators is crucial for writing sophisticated programming logic.

Complex AND (&&) Conditions

// AND operator examples
let age = 25;
let hasLicense = true;
let hasClearRecord = true;

// All conditions must be true
if (age >= 21 && hasLicense && hasClearRecord) {
    console.log("You can rent a car");
}

// Complex AND condition with comparisons
let score = 85;
let attendance = 95;
if (score >= 80 && attendance >= 90) {
    console.log("Student qualifies for honors");
}

Complex OR (||) Conditions

// OR operator examples
let isEmployee = false;
let isMember = true;
let isVIP = false;

// Any condition can be true
if (isEmployee || isMember || isVIP) {
    console.log("Access granted");
}

// Complex OR condition with comparisons
let creditScore = 650;
let income = 50000;
if (creditScore > 700 || income > 60000) {
    console.log("Loan pre-approved");
}

Combining AND and OR Operators

// Complex combinations
let age = 25;
let hasID = true;
let isWeekend = true;
let isMember = false;

// Complex condition with both && and ||
if ((age >= 21 && hasID) && (isWeekend || isMember)) {
    console.log("Welcome to the club");
}

// Using parentheses for proper grouping
let temperature = 75;
let isRaining = false;
let isHoliday = true;
if ((temperature > 70 && !isRaining) || isHoliday) {
    console.log("Let's go to the park");
}

Practice Questions

  1. What will be the output of the following condition?
    let x = 10;
    let y = 5;
    let z = 15;
    console.log((x > y && y < z) || (z < x));
  2. Write a condition that checks if:
    • A person is eligible for a premium credit card
    • Requirements: Credit score > 750 AND (Annual income > 50000 OR existing customer for > 5 years)
  3. Write a program that takes three sides of a triangle as input and checks if the triangle is valid. A triangle is valid if:
    The sum of any two sides is greater than the third side and
    All sides are greater than zero.
  4. Write a program to check if a number is:
    Greater than 50 and divisible by 7 or
    Less than 20 and an even number.

Key Points to Remember

  • Use parentheses to clearly group conditions and control operator precedence
  • AND (&&) has higher precedence than OR (||)
  • When combining multiple conditions, test each part separately first
  • Consider readability when writing complex conditions
  • Use meaningful variable names to make conditions more understandable

While Loops in JavaScript

While loops execute a block of code as long as a specified condition is true. They are useful when you don't know in advance how many times you need to execute the code.

Basic While Loop Syntax

// Basic while loop structure
let count = 0;
while (count < 5) {
    console.log("Count is: " + count);
    count++;
}

// While loop with conditional break
let number = 1;
while (true) {
    console.log(number);
    if (number >= 5) break;
    number++;
}

Practical Examples

// Example 1: Password attempt checker
let correctPassword = "secret123";
let attempt = prompt("Enter password:");
let attempts = 1;

while (attempt !== correctPassword && attempts < 3) {
    attempt = prompt("Wrong password. Try again:");
    attempts++;
}

// Example 2: Number guessing game
let targetNumber = Math.floor(Math.random() * 100) + 1;
let guess;
let tries = 0;

while (guess !== targetNumber) {
    guess = Number(prompt("Guess a number between 1 and 100:"));
    tries++;
    
    if (guess > targetNumber) {
        console.log("Too high!");
    } else if (guess < targetNumber) {
        console.log("Too low!");
    }
}

// Example 3: Processing array elements
let fruits = ["apple", "banana", "orange", "grape"];
let i = 0;

while (i < fruits.length) {
    console.log("Processing fruit: " + fruits[i]);
    i++;
}

Practice Exercises

  1. Write a program using a while loop to print numbers from 1 to 10.
  2. Write a program to print numbers from 10 to 1 in reverse order using a while loop.
  3. Write a program to print all even numbers between 1 and 20 using a while loop.
  4. Write a program to print the multiplication table of a number (e.g., 5) using a while loop.
  5. Write a while loop that prints all odd numbers between 1 and 20.

Key Points to Remember

  • Always ensure there's a way to exit the loop
  • Use while loops when the number of iterations is unknown
  • Use do...while when the code block should execute at least once
  • Be careful with the loop condition to avoid infinite loops
  • Consider using for loops instead if you know the number of iterations

Switch Statements in JavaScript

A switch statement is a control structure that performs different actions based on different conditions. It's an alternative to multiple if...else statements.

// Basic Switch Statement Structure
switch(expression) {
    case value1:
        // code block
        break;
    case value2:
        // code block
        break;
    default:
        // code block
}

Example with document.write()

let day = new Date().getDay();
document.write("<h3>Today is: </h3>");

switch(day) {
    case 0:
        document.write("Sunday");
        break;
    case 1:
        document.write("Monday");
        break;
    case 2:
        document.write("Tuesday");
        break;
    case 3:
        document.write("Wednesday");
        break;
    case 4:
        document.write("Thursday");
        break;
    case 5:
        document.write("Friday");
        break;
    case 6:
        document.write("Saturday");
        break;
    default:
        document.write("Invalid day");
}

Key Points

Practice Questions

  1. What will be the output of this switch statement if the value of grade is 'B'?
    switch(grade) {
        case 'A': document.write("Excellent!");
            break;
        case 'B': document.write("Good job!");
            break;
        default: document.write("Keep trying!");
    }
  2. What happens if you forget to include a break statement in a case?
  3. Write a switch statement that converts number grades (1-5) to letter grades (A-F)
  4. How does a switch statement differ from if...else statements?

Solutions

  1. Output will be: "Good job!"
  2. The code will continue executing into the next case (fall-through behavior)
  3. Example solution:
    switch(grade) {
        case 5: document.write("A"); break;
        case 4: document.write("B"); break;
        case 3: document.write("C"); break;
        case 2: document.write("D"); break;
        case 1: document.write("F"); break;
        default: document.write("Invalid grade");
    }
  4. Switch statements are often cleaner for multiple conditions that check a single value, while if...else is better for complex conditions

JavaScript Functions

A function is a block of code designed to perform a specific task. Functions are fundamental building blocks in JavaScript.

// Function Declaration
function functionName(parameters) {
    // code to be executed
    return value;
}

// Function Expression
const functionName = function(parameters) {
    // code to be executed
    return value;
}

// Arrow Function (ES6)
const functionName = (parameters) => {
    // code to be executed
    return value;
}

Function Example

function calculateArea(length, width) {
    return length * width;
}

document.write("Area of rectangle: " + calculateArea(5, 3));

Built-in Math Functions

Function Description Example Result
Math.abs() Returns absolute value Math.abs(-5) 5
Math.exp() Returns e^x Math.exp(1) 2.718
Math.floor() Rounds down to nearest integer Math.floor(5.7) 5
Math.ceil() Rounds up to nearest integer Math.ceil(5.1) 6
Math.sin() Returns sine of angle (radians) Math.sin(Math.PI/2) 1
Math.cos() Returns cosine of angle (radians) Math.cos(0) 1
Math.sqrt() Returns square root Math.sqrt(16) 4
Math.pow() Returns base to the exponent power Math.pow(2, 3) 8
Math.max() Returns largest number Math.max(1, 5, 3) 5
Math.min() Returns smallest number Math.min(1, 5, 3) 1
// Math Functions Examples
document.write("<h3>Math Function Examples:</h3>");
document.write("Absolute value of -5: " + Math.abs(-5) + "<br>");
document.write("e raised to power 2: " + Math.exp(2) + "<br>");
document.write("Floor of 5.7: " + Math.floor(5.7) + "<br>");
document.write("Ceiling of 5.1: " + Math.ceil(5.1) + "<br>");
document.write("Sine of 90 degrees: " + Math.sin(Math.PI/2) + "<br>");
document.write("Square root of 16: " + Math.sqrt(16) + "<br>");
document.write("2 raised to power 3: " + Math.pow(2,3) + "<br>");
document.write("Maximum of (2,5,1): " + Math.max(2,5,1) + "<br>");
document.write("Minimum of (2,5,1): " + Math.min(2,5,1) + "<br>");

Practice Questions

  1. Write a function that calculates the area of a circle using Math.PI and Math.pow()
  2. Create a function that finds the hypotenuse of a right triangle using Math.sqrt()
  3. What's the difference between Math.floor() and Math.ceil() for the number 7.3?
  4. Write a function that converts degrees to radians using Math functions

Sample Solutions

// Circle Area
function circleArea(radius) {
    return Math.PI * Math.pow(radius, 2);
}

// Hypotenuse
function hypotenuse(a, b) {
    return Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
}

// Degrees to Radians
function degreesToRadians(degrees) {
    return degrees * (Math.PI / 180);
}

JavaScript String Functions

String functions allow you to manipulate and transform text data. Here are the essential string functions:

let str = "Hello, World!";
Function Description Example Result
length Returns string length str.length 13
toUpperCase() Converts to uppercase str.toUpperCase() "HELLO, WORLD!"
toLowerCase() Converts to lowercase str.toLowerCase() "hello, world!"
charAt() Returns character at index str.charAt(0) "H"
concat() Joins strings together str.concat(" Welcome!") "Hello, World! Welcome!"
indexOf() Returns first occurrence index str.indexOf("o") 4
lastIndexOf() Returns last occurrence index str.lastIndexOf("o") 7
substring() Extracts part of string str.substring(0,5) "Hello"

HTML Formatting Methods (Deprecated but still supported)

Function Description Example Result
big() Makes text bigger str.big() <big>Hello, World!</big>
bold() Makes text bold str.bold() <b>Hello, World!</b>
fontcolor() Sets text color str.fontcolor("red") <font color="red">Hello, World!</font>
fontsize() Sets font size str.fontsize(5) <font size="5">Hello, World!</font>
italics() Makes text italic str.italics() <i>Hello, World!</i>
strike() Adds strikethrough str.strike() <strike>Hello, World!</strike>
sub() Makes text subscript str.sub() <sub>Hello, World!</sub>
sup() Makes text superscript str.sup() <sup>Hello, World!</sup>
// String Function Examples using document.write()
let text = "JavaScript";
document.write("<h3>String Function Examples:</h3>");
document.write("Original text: " + text + "<br>");
document.write("Length: " + text.length + "<br>");
document.write("Uppercase: " + text.toUpperCase() + "<br>");
document.write("Lowercase: " + text.toLowerCase() + "<br>");
document.write("Character at index 0: " + text.charAt(0) + "<br>");
document.write("Index of 'a': " + text.indexOf('a') + "<br>");
document.write("Last index of 'a': " + text.lastIndexOf('a') + "<br>");
document.write("Substring (0,4): " + text.substring(0,4) + "<br>");

// HTML Formatting Examples
document.write(text.bold() + "<br>");
document.write(text.italics() + "<br>");
document.write(text.fontcolor("blue") + "<br>");
document.write("Normal text with " + text.sup() + " superscript<br>");
document.write("Normal text with " + text.sub() + " subscript<br>");

Practice Questions

  1. Write a function that counts the number of vowels in a string
  2. Create a function that capitalizes the first letter of each word in a sentence
  3. Write a program that checks if a string is a palindrome using string functions
  4. How would you extract the domain from an email address using string functions?

Sample Solutions

// Count vowels
function countVowels(str) {
    return str.toLowerCase().match(/[aeiou]/g).length;
}

// Capitalize words
function capitalizeWords(str) {
    return str.split(' ')
              .map(word => word.charAt(0).toUpperCase() + 
                   word.substring(1).toLowerCase())
              .join(' ');
}

// Check palindrome
function isPalindrome(str) {
    str = str.toLowerCase().replace(/[^a-z0-9]/g, '');
    return str === str.split('').reverse().join('');
}

// Extract domain
function getDomain(email) {
    return email.substring(email.indexOf('@') + 1);
}

User-Defined Functions

Functions are reusable blocks of code that perform specific tasks. You can create your own functions to organize and simplify your code.

Basic Function Syntax

           function name(parameter1, parameter2, parameter3) {
  // code to be executed
}  
            
            // Basic function declaration
function sayHello() {
    console.log("Hello!");
}

// Function with parameters
function add(a, b) {
    return a + b;
}

// Calling functions
sayHello();           // Output: Hello!
let sum = add(5, 3);  // sum = 8

Practice Examples

               
                
                
                // Calculate area of rectangle
function calculateArea(length, width) {
    return length * width;
}

// Check if number is even
const isEven = (number) => {
    return number % 2 === 0;
}

// Greet user with custom message
function greetUser(name = "Guest") {
    return `Welcome, ${name}!`;
}

JavaScript Events

Events are actions that happen on a webpage, like clicking a button or loading a page. JavaScript can detect these events and respond to them.

Common JavaScript Events

Event Description Example
onclick When user clicks an element <button onclick="alert('Hello!')">Click Me</button>
onfocus When user clicks inside a form field <input onfocus="this.style.background='yellow'">
onblur When user leaves a form field <input onblur="checkValue()">
onchange When value of an input changes <select onchange="updatePrice()">
onmouseover When mouse moves over an element <div onmouseover="showTooltip()">
onmouseout When mouse leaves an element <div onmouseout="hideTooltip()">
onload When a page or image finishes loading <body onload="startApp()">
onselect When text is selected <input onselect="copyText()">
onsubmit When a form is submitted <form onsubmit="validateForm()">

Simple Examples

// Click Event Example
<button onclick="changeColor()">Change Color</button>

function changeColor() {
    document.body.style.backgroundColor = 'lightblue';
}

// Focus and Blur Example
<input type="text" 
    onfocus="this.style.backgroundColor='yellow'"
    onblur="this.style.backgroundColor='white'"
    placeholder="Type here...">

// Mouse Over/Out Example
<div onmouseover="this.style.color='red'"
     onmouseout="this.style.color='black'">
    Hover over me!
</div>

// Form Submit Example
<form onsubmit="return validateForm()">
    <input type="text" id="username">
    <button type="submit">Submit</button>
</form>

function validateForm() {
    let username = document.getElementById("username").value;
    if (username === "") {
        alert("Please enter a username");
        return false;
    }
    return true;
}

Key Points to Remember

  • Events make web pages interactive
  • You can respond to user actions (clicks, typing, etc.)
  • Each event can trigger a JavaScript function
  • Events can be added directly in HTML or through JavaScript

The 'this' Keyword in JavaScript

The 'this' keyword refers to the current object or context. Its value changes depending on how and where it's used.

// < button onclick="this.style.backgroundColor='yellow'" > onclick < /button >