JavaScript Introduction For Beginners
JavaScript Introduction For Beginners
- **Client-Side**: JavaScript is most commonly used on the client-side, meaning it runs in the user’s
web browser without needing any server interaction. This makes it ideal for creating responsive, user-
friendly interfaces.
- **Server-Side**: JavaScript can also run on the server using environments like Node.js. This allows
developers to use the same language for both front-end and back-end development.
Together, these technologies allow developers to create rich, engaging web experiences.
- **Text Editors**:
- **Visual Studio Code**: A free, open-source editor with a wide range of features like syntax
highlighting, debugging, and extensions.
- **Sublime Text**: A fast and lightweight text editor that supports various programming languages,
including JavaScript.
- **Atom**: An open-source text editor developed by GitHub with a strong community and
customizable interface.
- **Web Browsers**:
- **Google Chrome**: Known for its developer tools, which help in debugging and testing JavaScript
code.
- **Mozilla Firefox**: Another browser with excellent developer tools.
- **Safari and Edge**: Both also support JavaScript and offer developer tools.
- **Online Editors**: Tools like **CodePen**, **JSFiddle**, and **Repl.it** allow you to write and
test JavaScript directly in your browser without any setup.
- **Node.js**: An open-source, cross-platform JavaScript runtime environment that allows you to run
JavaScript outside of a browser. It’s commonly used for server-side scripting.
### **1.5 Writing Your First JavaScript Code**
JavaScript can be written directly in an HTML file or in an external `.js` file. Here are the different ways
you can add JavaScript to your web pages:
- **Inline JavaScript**:
Inline JavaScript is written directly within an HTML tag using the `onclick`, `onmouseover`, etc.,
attributes.
```html
<button onclick="alert('Hello, World!')">Click Me</button>
```
Here, the JavaScript code runs when the button is clicked.
- **Internal JavaScript**:
Internal JavaScript is placed within a `<script>` tag inside the HTML document.
```html
<html>
<head>
<title>My First JavaScript</title>
</head>
<body>
<h1>Welcome to JavaScript!</h1>
<script>
console.log("Hello, World!");
</script>
</body>
</html>
```
This code logs "Hello, World!" to the browser's console when the page is loaded.
- **External JavaScript**:
External JavaScript is written in a separate `.js` file, which is linked to the HTML document.
```html
<html>
<head>
<title>My First JavaScript</title>
<script src="script.js"></script>
</head>
<body>
<h1>Welcome to JavaScript!</h1>
</body>
</html>
```
- **script.js**:
```javascript
alert("Hello, World!");
```
The script is executed when the page loads, displaying an alert with the message "Hello, World!".
- **`var`**: Declares a variable that is function-scoped, meaning it’s available throughout the function
in which it is declared.
```javascript
var name = "John";
```
- **`let`**: Declares a block-scoped variable, which means it is only accessible within the block
(enclosed by `{}`) where it is defined. `let` is preferred over `var` in modern JavaScript because it
reduces the chance of bugs.
```javascript
let age = 30;
```
- **`const`**: Declares a block-scoped variable that cannot be reassigned after it’s been set. It’s used
for variables that should not change throughout the program.
```javascript
const pi = 3.14;
```
- **String**: A sequence of characters used to represent text. Strings are enclosed in quotes (`" "` or `'
'`).
```javascript
let name = "Alice";
```
- **Null**: Represents the intentional absence of any object value. It’s often used to indicate that a
variable should have no value.
```javascript
let salary = null;
```
- **Undefined**: A variable that has been declared but not yet assigned a value. It’s automatically
assigned by JavaScript.
```javascript
let jobTitle;
```
- **Symbol**: A unique and immutable primitive value introduced in ES6, used primarily as a unique
identifier for object properties.
```javascript
let sym = Symbol('foo');
```
- **BigInt**: A numeric data type that can represent integers with arbitrary precision. It’s used when
dealing with very large numbers.
```javascript
let bigNumber = 123456789012345678901234567890n;
```
`+=` (Addition Assignment): Adds the right-hand value to the left-hand variable and assigns the result
to the variable.
```javascript
let x = 10;
x += 5; // x is now 15
```
- `-=` (Subtraction Assignment): Subtracts the right-hand value from the left-hand variable and assigns
the result to the variable.
```javascript
let x = 10;
x -= 5; // x is now 5
```
- `*=` (Multiplication Assignment): Multiplies the left-hand variable by the right-hand value and
assigns the result to the variable.
```javascript
let x = 10;
x *= 5; // x is now 50
```
- `/=` (Division Assignment): Divides the left-hand variable by the right-hand value and assigns the
result to the variable.
```javascript
let x = 10;
x /= 5; // x is now 2
```
- `===` (Strict Equality): Checks if two values are equal and of the same type.
```javascript
let isEqual = (5 === "5"); // false
```
- `!=` (Inequality): Checks if two values are not equal, ignoring type.
```javascript
let isNotEqual = (5 != "5"); // false
```
- `!==` (Strict Inequality): Checks if two values are not equal or not of the same type.
```javascript
let isNotEqual = (5 !== "5"); // true
```
- `>` (Greater Than): Checks if the left-hand value is greater than the right-hand value.
```javascript
let isGreater = (10 > 5); // true
```
- `<` (Less Than): Checks if the left-hand value is less than the right-hand value.
```javascript
let isLess = (10 < 5); // false
```
- `>=` (Greater Than or Equal To): Checks if the left-hand value is greater than or equal to the right-
hand value.
```javascript
let isGreaterOrEqual = (10 >= 5); // true
```
- `<=` (Less Than or Equal To): Checks if the left-hand value is less than or equal to the right-hand
value.
```javascript
let isLessOrEqual = (10 <= 5); // false
```
#### **Concatenation**
Concatenation is the process of combining two or more strings.
- **Subtraction**:
```javascript
let difference = 10 - 5; // 5
```
- **Multiplication**:
```javascript
let product = 10 * 5; // 50
```
- **Division**:
```javascript
let quotient = 10 / 5; // 2
```
- **Modulus**:
```javascript
let remainder = 10 % 3; // 1
```
- **else Statement**: Executes a block of code if the condition in the `if` statement is false.
```javascript
let age = 15;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
```
```javascript
let day = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
case 4:
console.log("Thursday");
break;
case 5:
console.log("Friday");
break;
default:
console.log("Weekend");
}
```
```javascript
for (let i = 0; i < 5; i++) {
console.log("Iteration: " + i);
}
```
```javascript
let i = 0;
while (i < 5) {
console.log("Iteration: " + i);
i++;
}
```
- **continue**: Skips the rest of the loop iteration and proceeds to the next iteration.
```javascript
for (let i = 0; i < 5; i++) {
if (i === 3) {
continue;
}
console.log("Iteration: " + i);
}
```
## **5. Functions**
```javascript
function greet() {
console.log("Hello, World!");
}
```
```javascript
greet(); // Outputs: Hello, World!
```
```javascript
function add(a, b) {
return a + b;
}
```javascript
let greet = function(name) {
console.log("Hello, " + name + "!");
};
```javascript
let add = (a, b) => a + b;
```javascript
function myFunction() {
let message = "Hello";
console.log(message); // Outputs: Hello
}
```javascript
function higherOrder(func) {
func();
}
function greet() {
console.log("Hello!");
}
```javascript
let colors = ["Red", "Green", "Blue"];
```
```javascript
let firstColor = colors[0]; // "Red"
```
```javascript
let person = {
firstName: "John",
lastName: "Doe",
age: 25,
greet: function() {
console.log("Hello, " + this.firstName + "!");
}
};
```
```javascript
let name = person.firstName; // "John"
let age = person["age"]; // 25
```
```javascript
person.job = "Developer";
person.age = 30;
```
```javascript
delete person.age;
```
```javascript
person.greet(); // Outputs: Hello, John!
```
- **style**
## **8. Events**
- **Capturing Phase**: The event starts from the root and goes down to the target element.
- **Bubbling Phase**: The event starts from the target element and bubbles up to the root.
```javascript
document.getElementById("parent").addEventListener("click", function(event) {
if (event.target && event.target.nodeName == "BUTTON") {
alert("Button clicked!");
}
});
```
```javascript
try {
let result = riskyFunction();
} catch (error) {
console.log("An error occurred: " + error.message);
} finally {
console.log("This will always run.");
}
```
```javascript
function divide(a, b) {
if (b === 0) {
throw new Error("Division by zero");
}
return a / b;
}
try {
let result = divide(4, 0);
} catch (error) {
console.log("An error occurred: " + error.message);
}
```
```javascript
function fetchData(callback) {
setTimeout(function() {
callback("Data received");
}, 2000);
}
fetchData(function(data) {
console.log(data); // Outputs: Data received
});
```
```javascript
let promise = new Promise(function(resolve, reject) {
let success = true;
if (success) {
resolve("Data received");
} else {
reject("Error occurred");
}
});
promise.then(function(data) {
console.log(data); // Outputs: Data received
}).catch(function(error) {
console.log(error);
});
```
```javascript
async function fetchData() {
let data = await fetch("https://api.example.com/data");
let result = await data.json();
console.log(result);
}
fetchData();
```
## **Conclusion**
This JavaScript course for beginners covers the fundamental concepts and features of the language.
By the end of the course, students should have a solid understanding of variables, data types,
operators, functions, control flow, arrays, objects, DOM manipulation, events, error handling, and
asynchronous programming. These topics form the foundation for further exploration and
development in JavaScript.
## **Next Steps**
After completing this course, students should practice by building small projects, such as a simple
calculator, a to-do list, or a quiz app. These projects will help reinforce the concepts learned and
provide hands-on experience with JavaScript.
If students want to continue their learning journey, they can explore more advanced topics such as
ES6 features, working with APIs, JavaScript frameworks (e.g., React, Angular, Vue), and server-side
JavaScript with Node.js.
Good luck, and happy coding!