- 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 Data Types
JavaScript Data Types
JavaScript is a dynamically typed language, meaning variables can hold values of different data types. Here are the main data types in JavaScript:
1. Primitive Data Types:
- Number
- String
- Boolean
- Null
- Undefined
- Symbol (added in ECMAScript 6)
2. Composite Data Types:
- Object
- Function
1. Number
The number data type represents numeric values. It includes integers, floating-point numbers, and special numeric values like Infinity and NaN (Not a Number).
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Number Data Type Example</title>
</head>
<body>
<script>
let num = 42; // Integer
let floatNum = 3.14; // Floating-point number
let infinityValue = Infinity; // Represents infinity
let notANumber = NaN; // Represents not a number
</script>
</body>
</html>
2. String
The string data type represents textual data enclosed in single (') or double (") quotes.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>String Data Type Example</title>
</head>
<body>
<script>
let str1 = 'Hello, World!'; // Single quotes
let str2 = "JavaScript is awesome!"; // Double quotes
</script>
</body>
</html>
3. Boolean
The boolean data type represents a logical entity and can have two values: true or false.
Example:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Boolean Data Type Example</title>
</head>
<body>
<script>
let isCodingFun = true; // True value
let isPlayingGames = false; // False value
</script>
</body>
</html>
4. Null and Undefined
- null: Represents the intentional absence of any object value.
- undefined: Represents a variable that has been declared but not assigned a value.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Null and Undefined Data Types Example</title>
</head>
<body>
<script>
let nullValue = null; // Represents null
let undefinedValue; // Represents undefined
</script>
</body>
</html>
5. Symbol (added in ECMAScript 6) Symbols are unique and immutable data types introduced in ECMAScript 6.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Symbol Data Type Example</title>
</head>
<body>
<script>
let sym1 = Symbol('key1'); // Creating a symbol with description
let sym2 = Symbol('key2'); // Creating another symbol
</script>
</body>
</html>
6. Object Objects are complex data types that represent a collection of properties and methods. They are used to store various data structures.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Object Data Type Example</title>
</head>
<body>
<script>
let person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
email: 'john.doe@example.com'
};
</script>
</body>
</html>
7. Function
Functions are special objects used to define reusable blocks of code.
Example:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Function Data Type Example</title>
</head>
<body>
<script>
function greet(name) {
return 'Hello, ' + name + '!';
}
</script>
</body>
</html>
Practice Excercise Practice now
The Concept Of Data Types
JavaScript, as a versatile programming language for the web, plays a crucial role in manipulating HTML elements and handling data types within the context of web development. While HTML provides the structure and content of a web page, JavaScript brings interactivity and dynamic behavior to the web. Understanding how JavaScript handles data types when interacting with HTML is essential for building responsive and functional web applications. This discussion will explore the concept of data types in JavaScript, particularly focusing on how these types are used and manipulated within HTML contexts, accompanied by relevant examples.
Basic Data Types in JavaScript
JavaScript supports several basic data types, including:
- Number: Represents both integer and floating-point numbers.
- String: Represents text enclosed in single or double quotes.
- Boolean: Represents logical values true and false.
- Null: Represents an intentional absence of any object value.
- Undefined: Represents a variable that has been declared but not yet assigned a value.
- Object: Represents a collection of properties.
- Symbol: Represents a unique and immutable value (introduced in ES6).
Number
The number type can handle both integers and floating-point numbers.
let age = 30;
let price = 19.99;
String
Strings are used to represent textual data.
let greeting = 'Hello, world!';
Boolean
Booleans represent true/false values.
let isStudent = true;
let hasLicense = false;
Null and Undefined
null and undefined represent the absence of a value and an uninitialized variable, respectively.
let user = null;
let score;
Object
Objects are collections of properties, defined as key-value pairs.
let person = {
firstName: "John",
lastName: "Doe",
age: 25
};
Symbol
Symbols are unique identifiers used for object properties.
Interacting with HTML Elements
JavaScript interacts with HTML elements using the Document Object Model (DOM). Here, we demonstrate how JavaScript handles different data types when working with HTML elements.
Modifying Text Content
To modify the text content of an HTML element, you can use the textContent or innerText property.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Data Types</title>
</head>
<body>
<p id="greet">Hello!</p>
<script>
let greeting = "Welcome to JavaScript!";
document.getElementById("greet").textContent = greeting;
</script>
</body>
</html>
Working with Numbers
JavaScript can manipulate numerical data and reflect changes in the HTML.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Numbers</title>
</head>
<body>
<p id="number">Initial Value: 0</p>
<button onclick="increment()">Increment</button>
<script>
let count = 0;
function increment() {
count += 1;
document.getElementById("number").textContent = "Current Value: " + count;
}
</script>
</body>
</html>
Boolean Operations
Booleans are often used to control the visibility of HTML elements.
<html>
<head>
<title>JavaScript Booleans</title>
</head>
<body>
<p id="message">This is a secret message.</p>
<button onclick="toggleMessage()">Toggle Message</button>
<script>
let isVisible = true;
function toggleMessage() {
isVisible = !isVisible;
document.getElementById("message").style.display = isVisible ? "block" : "none";
}
</script>
</body>
</html>
Handling Null and Undefined
JavaScript can handle null and undefined values when updating the HTML.
<html>
<head>
<title>JavaScript Null and Undefined</title>
</head>
<body>
<p id="status">Status: Not Defined</p>
<button onclick="updateStatus()">Update Status</button>
<script>
let status = null;
function updateStatus() {
if (status === null) {
status = "Active";
} else {
status = null;
}
document.getElementById("status").textContent = "Status: " + (status || "Not Defined");
}
</script>
</body>
</html>
Objects in JavaScript
Objects can be used to store and display complex data structures.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Objects</title>
</head>
<body>
<p id="person"></p>
<button onclick="showPerson()">Show Person</button>
<script>
let person = {
firstName: "Jane",
lastName: "Doe",
age: 28
};
function showPerson() {
document.getElementById("person").textContent = `Name: ${person.firstName} ${person.lastName}, Age: ${person.age}`;
}
</script>
</body>
</html>
Symbols
Symbols are less commonly used in the DOM but can uniquely identify properties in objects.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Symbols</title>
</head>
<body>
<p id="symbol"></p>
<script>
let mySymbol = Symbol('example');
let obj = {};
obj[mySymbol] = "Symbol Value";
document.getElementById("symbol").textContent = obj[mySymbol];
</script>
</body>
</html>
Advanced Interactions
Form Validation
JavaScript can validate form data before submission to ensure data types are correct.
<html>
<head>
<title>Form Validation</title>
</head>
<body>
<form onsubmit="return validateForm()">
<label for="age">Age:</label>
<input type="text" id="age" name="age">
<input type="submit" value="Submit">
</form>
<p id="error"></p>
<script>
function validateForm() {
let age = document.getElementById("age").value;
if (isNaN(age) || age < 0 || age > 120) {
document.getElementById("error").textContent = "Please enter a valid age.";
return false;
}
return true;
}
</script>
</body>
</html>
Dynamic Content Generation
JavaScript can dynamically create and manipulate HTML elements based on data types.
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Content</title>
</head>
<body>
<ul id="list"></ul>
<button onclick="addItem()">Add Item</button>
<script>
let items = ["Item 1", "Item 2", "Item 3"];
function addItem() {
let ul = document.getElementById("list");
items.forEach(item => {
let li = document.createElement("li");
li.textContent = item;
ul.appendChild(li);
});
}
</script>
</body>
</html>
Practice Excercise Practice now
JavaScript Types Are Dynamic
JavaScript is a dynamically typed language, meaning that variable types are determined at runtime, and variables can change types during the execution of the program. This flexibility allows for rapid development and easy manipulation of data but can also lead to unexpected behavior if not managed carefully.
What Does Dynamic Typing Mean?
In statically typed languages like Java or C#, the type of a variable is known at compile time and cannot change. In dynamically typed languages like JavaScript, the type of a variable is determined at runtime, and the same variable can hold different types of values at different times during the execution of the program.
Declaring Variables in JavaScript
In JavaScript, variables can be declared using the var, let, or const keywords. The var keyword is function-scoped and can lead to issues with hoisting, while let and const are block-scoped and provide better scoping rules.
let x = 42; // x is a number
x = 'Hello'; // x is now a string
x = true; // x is now a boolean
In the example above, the variable x starts as a number, then becomes a string, and finally a boolean. This demonstrates the dynamic nature of JavaScript variables.
Type Checking with typeof
JavaScript provides the typeof operator to check the type of a variable at runtime.
let y = 5;
console.log(typeof y); // "number"
y = 'world';
console.log(typeof y); // "string"
y = null;
console.log(typeof y); // "object" (this is a historical bug in JavaScript)
The typeof operator is useful for debugging and ensuring that variables are of the expected type.
Type Coercion
JavaScript performs automatic type conversion, known as type coercion, which can lead to unexpected results. For example, when using the + operator, JavaScript converts the operands to strings if one of them is a string.
let b = '5';
let c = a + b; // '105' (number 10 is coerced to string '10')
Other arithmetic operators, such as -, *, and /, do not perform this coercion.
let e = '5';
let f = d - e; // 5 (string '5' is coerced to number 5)
Converting Data Types Explicitly
While JavaScript handles type conversion automatically, it is often better to perform explicit type conversion to avoid unexpected results.
String to Number Conversion:
let h = Number(g); // 123 (number)
let i = parseInt(g); // 123 (integer)
let j = parseFloat(g); // 123 (floating-point number)
Number to String Conversion:
let l = String(k); // '456'
let m = k.toString(); // '456'
Boolean Conversion:
let n = 0;
let o = Boolean(n); // false (0 is falsy)
let p = 1;
let q = Boolean(p); // true (1 is truthy)
Using Dynamic Types in Functions
Dynamic typing is particularly useful in functions where the input type may vary.
return a + b;
}
console.log(add(2, 3)); // 5 (number addition)
console.log(add('2', '3')); // '23' (string concatenation)
console.log(add(2, '3')); // '23' (number to string conversion and concatenation)
In the add function, the parameters a and b can be either numbers or strings, and the function behaves differently based on their types.
Handling Dynamic Types with Type Checking
To handle dynamic types more effectively, you can use type checking within your functions.
function addStrict(a, b) {
if (typeof a === 'number' && typeof b === 'number') {
return a + b;
} else {
throw new Error('Both arguments must be numbers');
}
}
console.log(addStrict(2, 3)); // 5
console.log(addStrict('2', '3')); // Error: Both arguments must be numbers
By checking the types of a and b before performing the addition, you can ensure that the function only operates on numbers and prevent unintended behavior.
Common Pitfalls and Best Practices
Pitfall: Unexpected Type Coercion
console.log(2 - '2'); // 0 (string to number coercion)
Best Practice: Use Strict Equality (===)
console.log(2 === '2'); // false (strict equality, no type coercion)
Pitfall: null and undefined Confusion
console.log(r == null); // true (undefined is equal to null)
console.log(r === null); // false (strict equality)
Best Practice: Explicitly Check for null and undefined
console.log('r is undefined');
}
if (r === null) {
console.log('r is null');
}
Practice Excercise Practice now
The Typeof Operator
The typeof operator in JavaScript is a useful tool for identifying the data type of a given variable or expression. Understanding how to effectively use the typeof operator is crucial for debugging and writing robust code. This article delves into the intricacies of the typeof operator, providing examples and explanations to illustrate its use.
Basic Usage of typeof
The typeof operator returns a string indicating the type of the operand. Here is the basic syntax:
typeof operand
The operand can be a variable, a literal, or an expression. The typeof operator is often used to check the type of variables in conditional statements and debugging.
Common Data Types
JavaScript has several built-in types, and typeof can identify most of them. Here are the common types and their typeof results:
console.log(typeof 42); // "number"
console.log(typeof 'hello'); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof { name: 'John' }); // "object"
console.log(typeof [1, 2, 3]); // "object" (arrays are objects)
console.log(typeof function() {}); // "function"
console.log(typeof null); // "object" (this is a well-known bug)
console.log(typeof Symbol('id')); // "symbol"
Detailed Examples
Numbers and Strings
JavaScript treats numbers and strings as distinct types. The typeof operator can easily distinguish between them.
let age = 30;
let name = "Alice";
console.log(typeof age); // "number"
console.log(typeof name); // "string"
Booleans
Booleans represent logical values and can be either true or false.
let isUser = false;
console.log(typeof isAdmin); // "boolean"
console.log(typeof isUser); // "boolean"
Undefined
A variable that has been declared but not assigned a value is of type undefined.
console.log(typeof score); // "undefined"
Objects and Arrays
Both objects and arrays are of type object. However, arrays can be distinguished using the Array.isArray method.
let numbers = [1, 2, 3];
console.log(typeof user); // "object"
console.log(typeof numbers); // "object"
console.log(Array.isArray(numbers)); // true
Functions
Functions are a special type of object and are identified as function by the typeof operator.
return "Hello!";
}
console.log(typeof greet); // "function"
Symbols
Symbols are unique and immutable data types introduced in ECMAScript 2015 (ES6).
console.log(typeof id); // "symbol"
Null
Null is a special value representing "no value" or "empty". It is considered an object due to a historical bug in JavaScript.
console.log(typeof emptyValue); // "object"
Using typeof in Conditional Statements
The typeof operator is often used in conditional statements to ensure that variables are of the expected type before performing operations on them.
if (typeof a === 'number' && typeof b === 'number') {
return a + b;
} else {
return "Both arguments must be numbers.";
}
}
console.log(add(10, 20)); // 30
console.log(add(10, '20')); // "Both arguments must be numbers."
Checking for Undefined Variables
You can use typeof to check if a variable is undefined without causing a ReferenceError if the variable has not been declared.
if (typeof someVariable === 'undefined') {
console.log('someVariable is not defined');
}
Avoiding typeof Pitfalls
While the typeof operator is straightforward, there are a few quirks and pitfalls to be aware of:
Null Values: As mentioned, typeof null returns "object". This behavior is a bug in JavaScript but has been retained for backward compatibility.
console.log(typeof nothing); // "object"
Arrays: Arrays are objects, so typeof returns "object". To specifically check for arrays,
use Array.isArray.
console.log(typeof items); // "object"
console.log(Array.isArray(items)); // true
Functions: Functions are technically objects, but typeof correctly identifies them as "function".
function example() {}
console.log(typeof example); // "function"
Combining typeof with Other Type Checking Methods
In some cases, you might need more precise type checking than what typeof provides. JavaScript offers other methods that can be combined with typeof for robust type checking.
Instanceof Operator
The instanceof operator tests whether an object is an instance of a specific class or constructor function.
console.log(date instanceof Date); // true
console.log(date instanceof Object); // true
Constructor Property
You can use the constructor property to determine the constructor function of an object.
console.log(array.constructor === Array); // true
console.log(array.constructor === Object); // false
Custom Type Checking Functions
For more complex scenarios, you can create custom type-checking functions.
return typeof value === 'number' && isFinite(value);
}
console.log(isNumber(123)); // true
console.log(isNumber('123')); // false
console.log(isNumber(NaN)); // false
Practice Excercise Practice now
Difference Between Undefined And Null
he concepts of "undefined" and "null" are fundamental in JavaScript, representing different states or values within the language. Let's delve into their differences, use cases, and examples.
Understanding "Undefined" and "Null"
Undefined:
In JavaScript, "undefined" is a primitive data type. It signifies that a variable has been declared but has not been assigned a value or initialized. Essentially, it represents the absence of a value. Variables that are not assigned a value automatically default to "undefined."
console.log(x); // Output: undefined
In this example, the variable x is declared but not assigned a value, resulting in its value being "undefined."
Null:
On the other hand, "null" is also a primitive data type, but it represents the intentional absence of any value. Unlike "undefined," which typically occurs due to variables not being initialized, "null" is explicitly set to indicate no value or absence of an object reference.
console.log(y); // Output: null
Here, the variable y is explicitly assigned the value "null," indicating that it intentionally does not have any value.
Differences Between "Undefined" and "Null"
Origin of Value:
- "Undefined" occurs when a variable is declared but not initialized.
- "Null" is explicitly assigned to indicate no value or absence of an object reference.
- Type:
- "Undefined" is a primitive data type in JavaScript.
- "Null" is also a primitive data type in JavaScript.
- "Undefined" typically represents an unintentional absence of value, often used when a variable's value is expected but not provided.
- "Null" represents a deliberate absence of value or no reference to an object, commonly used to reset or clear a variable or property.
Undefined:
let z; // Variable declared but not initialized
console.log(z); // Output: undefined
function testFunction() {
let a; // Variable declared but not initialized
console.log(a); // Output: undefined
}
testFunction();
In this example, both variable z and variable a inside the testFunction are declared but not initialized, resulting in their values being "undefined."
Null:
console.log(person); // Output: null
let obj = {
name: "John",
age: 30
};
obj = null; // Clearing the object reference
console.log(obj); // Output: null
Here, person is explicitly set to "null," indicating no value or absence of an object reference. Similarly, the obj object reference is cleared by assigning it the value "null."
Comparison and Equality:
When comparing "undefined" and "null," they are not strictly equal (===) because they represent different states:
console.log(undefined === null); // Output: false
console.log(undefined == null); // Output: true (loose equality)
The loose equality (==) operator considers "undefined" and "null" as equal, but the strict equality (===) operator does not because they are distinct primitive types.
Use Cases:
Undefined:
- Default value when a variable is declared but not initialized.
- Returned by functions that don't explicitly return a value.
- Indicates a missing or unspecified value.
- Explicitly used to represent no value or absence of an object.
- Often used to clear or reset object references.
- Can be used in conditional checks to indicate absence of an object reference.
Practice Excercise Practice now
Primitive Data
JavaScript is a versatile programming language that supports various data types and operators. In this explanation, we'll delve into primitive data types and operators in JavaScript, exploring their characteristics and usage with examples.
Primitive Data Types in JavaScript
JavaScript has six primitive data types:
- Number: Represents numeric values. It includes integers and floating-point numbers.
- String: Represents textual data enclosed in single or double quotes.
- Boolean: Represents a logical value, either true or false.
- Undefined: Represents a variable that has been declared but not assigned a value.
- Null: Represents an intentional absence of any value.
- Symbol: Represents a unique identifier introduced in ECMAScript 6.
Operators in JavaScript
JavaScript includes various operators to perform operations on data. Here are some common operators:
Arithmetic Operators: Used for arithmetic calculations like addition (+), subtraction (-), multiplication (*), division (/), and modulus (%).
Comparison Operators: Used to compare values and return a boolean result. Examples include equal to (==), not equal to (!=), strict equal to (===), greater than (>), less than (<), etc.
Logical Operators: Used for logical operations. Includes AND (&&), OR (||), and NOT (!).
Assignment Operators: Used to assign values to variables. Examples are the assignment operator (=), addition assignment (+=), subtraction assignment (-=), etc.
Unary Operators: Operators that work on a single operand. Examples are the increment (++) and decrement (--) operators.
Ternary Operator (Conditional Operator): Used for conditional expressions. It has the syntax condition ? value1 : value2.
Bitwise Operators: Used to perform bitwise operations on integers. Examples include bitwise AND (&), bitwise OR (|), bitwise XOR (^), etc.
Examples and Explanation
Number Data Type and Arithmetic Operators
let num1 = 10;
let num2 = 5;
let sum = num1 + num2; // Addition
let difference = num1 - num2; // Subtraction
let product = num1 * num2; // Multiplication
let quotient = num1 / num2; // Division
let remainder = num1 % num2; // Modulus
In this example, we use the number data type and arithmetic operators to perform basic mathematical operations.
String Data Type and Concatenation Operator
let lastName = "Doe";
let fullName = firstName + " " + lastName; // Concatenation
Here, we use the string data type and the concatenation operator (+) to combine two strings.
Boolean Data Type and Comparison Operators
let isAdult = age >= 18; // Greater than or equal to comparison
let isValid = true;
let isInvalid = !isValid; // Logical NOT operator
In this snippet, we use the boolean data type and comparison/logical operators to evaluate conditions and determine boolean values.
Undefined and Null Data Types
let nullVar = null; // Null variable
Here, we declare an undefined variable and explicitly assign null to another variable.
Symbol Data Type
let obj = {
[key]: "value"
};
In this example, we use symbols as unique property keys in an object.
Ternary Operator
let result = num % 2 === 0 ? "Even" : "Odd";
This code snippet uses the ternary operator to check if a number is even or odd and assigns the result accordingly.
Bitwise Operators
let b = 3; // 0011
let bitwiseAnd = a & b; // Bitwise AND (0001)
let bitwiseOr = a | b; // Bitwise OR (0111)
let bitwiseXor = a ^ b; // Bitwise XOR (0110)
These examples demonstrate bitwise AND, OR, and XOR operations on binary numbers.
Practice Excercise Practice now
Complex Data
JavaScript objects are complex data types that allow you to store and manipulate collections of data and functionalities. An object is defined by a set of key-value pairs, where each key is a unique identifier (property) and each value can be any data type, including other objects. Here's an example of an object representing a person:
name: "John Doe",
age: 30,
email: "johndoe@example.com",
address: {
street: "123 Main St",
city: "Anytown",
country: "USA"
},
hobbies: ["Reading", "Gardening", "Cooking"]
};
In this example, person is an object with properties like name, age, email, address, and hobbies. The address property is itself an object containing street, city, and country properties. The hobbies property is an array containing multiple values.
You can access object properties using dot notation (objectName.propertyName) or bracket notation (objectName['propertyName']). For example:
console.log(person.name); // Outputs: "John Doe"
console.log(person.address.city); // Outputs: "Anytown"
console.log(person['hobbies'][0]); // Outputs: "Reading"
Arrays in JavaScript
Arrays are another complex data type in JavaScript used to store collections of values, which can be of any data type. Arrays are ordered, meaning the elements are indexed starting from 0. Here's an example of an array:
You can access array elements using their index. For example:
console.log(fruits.length); // Outputs: 4 (length of the array)
fruits.push("Grapes"); // Adds "Grapes" to the end of the array
console.log(fruits); // Outputs: ["Apple", "Banana", "Orange", "Mango", "Grapes"]
Functions in JavaScript
Functions are blocks of reusable code that perform a specific task when called. They can accept parameters (inputs) and return values (outputs). Functions can be defined using function declarations or function expressions. Here's an example of a function declaration:
return `Hello, ${name}!`;
}
console.log(greet("Alice")); // Outputs: "Hello, Alice!"
You can also define functions using function expressions:
return a * b;
};
console.log(multiply(5, 3)); // Outputs: 15
Using Complex Data Types in HTML
You can incorporate complex data types like objects, arrays, and functions into HTML documents using JavaScript. Here's an example of how you might do that:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Complex Data Types in HTML</title>
</head>
<body>
<div id="output"></div>
<script>
// Define an object representing a person
let person = {
name: "John Doe",
age: 30,
email: "johndoe@example.com",
hobbies: ["Reading", "Gardening", "Cooking"],
greet: function() {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
}
};
// Access and display object properties in HTML
document.getElementById("output").innerHTML = `
<h1>${person.name}</h1>
<p>Email: ${person.email}</p>
<p>Hobbies: ${person.hobbies.join(", ")}</p>
<p>${person.greet()}</p>
`;
</script>
</body>
</html>
Practice Excercise Practice now
Products
Partner
Copyright © RVR Innovations LLP 2024 | All rights reserved - Mytat.co is the venture of RVR Innovations LLP