<script>
tag.
<html>
<body>
<h1>My Web Page</h1>
<script>
console.log("Hello, World!");
</script>
</body>
</html>
src
attribute in the <script>
tag.
<html>
<body>
<h1>My Web Page</h1>
<script src="script.js"></script>
</body>
</html>
Note: Ensure the script.js
file is in the same directory as your HTML file, or specify the correct path.
<script>
tag inside the <head>
section of your HTML file.
<html>
<head>
<script>
console.log("Hello from the head section!");
</script>
</head>
<body>
<h1>My Web Page</h1>
</body>
</html>
Note: It’s generally a good practice to place JavaScript at the end of the body for better performance unless it needs to run early.
console.log
, prompt
, and alert
console.log
:
This function is used to print or log messages to the browser’s console (useful for debugging).
console.log("This is a log message!");
prompt
:
This function displays a dialog box that prompts the user for input.
let userInput = prompt("Enter your name:");
console.log("User's name is " + userInput);
alert
:
This function displays a simple message in a dialog box.
alert("This is an alert message!");
var
:
Older way of declaring variables. It has function scope and can be redeclared.
var name = "John";
console.log(name);
let
:
Modern way of declaring variables. It has block scope and cannot be redeclared in the same block.
let age = 25;
console.log(age);
const
:
Declares a constant variable that cannot be reassigned after its initial assignment. It also has block scope.
const pi = 3.14;
console.log(pi);
Note: Use let
and const
for variable declarations in modern JavaScript, as they provide better scoping and prevent errors.
JavaScript has different data types, which can be categorized into two main types: Primitive and Non-Primitive (Reference).
let greeting = "Hello, World!";
let age = 30;
let price = 9.99;
true
or false
.
let isAvailable = true;
let name;
console.log(name); // Output: undefined
let value = null;
let sym = Symbol("id");
let bigNumber = BigInt(9007199254740991);
let person = {
name: "John",
age: 30
};
let fruits = ["Apple", "Banana", "Mango"];
function greet() {
console.log("Hello, World!");
}
let person = {
firstName: "John",
lastName: "Doe",
age: 30
};
console.log(person.firstName); // Dot notation
console.log(person["lastName"]); // Bracket notation
person.job = "Developer"; // Adding a new property
person.age = 31; // Modifying an existing property
console.log(person);
delete
keyword.
delete person.age;
console.log(person);