JavaScript Tutorial: From Basic to Advanced
JavaScript Tutorial: From Basic to Advanced
1. Basic Concepts
Declaring Variables:
In JavaScript, we declare variables using var
, let
, or const
. let
and const
are the modern way to declare variables.
let name = ""; // Declaring a string variable.
const pi = 3.14; // Declaring a constant.
Data Types:
JavaScript has several data types, including:
- Primitive types:
String
,Number
,Boolean
,Null
,Undefined
,Symbol
. - Object types:
Object
,Array
,Function
.
let name = "Krish"; // String type
let age = 25; // Number type
let isStudent = true; // Boolean type
Basic Output:
We can output data to the console using console.log()
:
console.log(name); // Output the value of the variable "name"
2. Data Type Conversion
parseInt() and parseFloat():
These functions are used to convert strings to numbers.
console.log(parseInt("3")); // Converts string "3" to number 3.
console.log(parseFloat("3.14")); // Converts string "3.14" to number 3.14.
isNaN():
The isNaN()
function checks whether a value is NaN (Not a Number).
console.log(isNaN("abc")); // Returns true because "abc" is not a number.
3. Conditional Statements
If-Else Statements:
We use if-else
statements to make decisions based on conditions.
let age = 18;
if (age >= 18) {
console.log("Person can drive");
} else {
console.log("Person can't drive");
}
Ternary Operator:
A shorter way to write an if-else
statement using condition ? value_if_true : value_if_false
.
let score = 70;
let result = score >= 50 ? "Passed" : "Failed";
console.log(result);
4. Logical Operators
AND (&&
) and OR (||
):
Logical operators help combine multiple conditions.
let age = 18;
let citizen = true;
let canVote = age >= 18 && citizen; // true because both conditions are true
Short-circuiting:
JavaScript evaluates expressions using short-circuit logic.
console.log(true && false); // false
console.log(true || false); // true
5. Loops
For Loop:
A basic loop to iterate over a range of values.
for (let i = 0; i < 5; i++) {
console.log(i); // Prints numbers 0 to 4
}
While Loop:
A loop that continues as long as the condition is true.
let i = 0;
while (i < 3) {
console.log(i); // Prints numbers 0 to 2
i++;
}
Do-While Loop:
Similar to the while
loop, but it guarantees at least one iteration.
let i = 0;
do {
console.log(i); // Prints 0 once before checking the condition
i++;
} while (i < 3);
6. Arrays and Array Methods
Array Creation:
Arrays store multiple values.
let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[0]); // Output: "Apple"
Array Methods:
- map(): Transforms each element in the array.
let numbers = [1, 2, 3];
let doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [2, 4, 6]
- filter(): Filters elements based on a condition.
let numbers = [1, 2, 3, 4, 5];
let evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]
- forEach(): Executes a function on each element.
let numbers = [1, 2, 3];
numbers.forEach(num => console.log(num)); // Output: 1 2 3
- reduce(): Reduces the array to a single value.
let numbers = [1, 2, 3, 4];
let sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // Output: 10
- slice(): Extracts part of an array.
let fruits = ["Apple", "Banana", "Cherry"];
let slicedFruits = fruits.slice(1, 3);
console.log(slicedFruits); // Output: ["Banana", "Cherry"]
- splice(): Adds/removes elements from an array.
let fruits = ["Apple", "Banana", "Cherry"];
fruits.splice(1, 1, "Orange");
console.log(fruits); // Output: ["Apple", "Orange", "Cherry"]
7. Functions
Function Declaration:
Functions allow you to encapsulate reusable code.
function greet(name) {
return "Hello " + name;
}
console.log(greet("Krish")); // Output: Hello Krish
Arrow Functions:
A concise syntax for writing functions.
const greet = (name) => "Hello " + name;
console.log(greet("Krish")); // Output: Hello Krish
Default Parameters:
Functions can have default values for parameters.
const greet = (name = "Guest") => "Hello " + name;
console.log(greet()); // Output: Hello Guest
8. Objects
Creating Objects:
Objects are collections of key-value pairs.
let person = {
name: "Krish",
age: 25,
greet: function() {
return "Hello, " + this.name;
}
};
console.log(person.name); // Output: Krish
console.log(person.greet()); // Output: Hello, Krish
9. String Manipulation
String Methods:
JavaScript provides useful methods to manipulate strings:
let text = " Hello World ";
console.log(text.trim()); // Removes whitespace: "Hello World"
console.log(text.toUpperCase()); // Converts to uppercase: "HELLO WORLD"
console.log(text.toLowerCase()); // Converts to lowercase: "hello world"
console.log(text.includes("Hello")); // Checks if string includes "Hello": true
console.log(text.replace("World", "JavaScript")); // Replace part of a string: "Hello JavaScript"
10. Advanced Concepts
Destructuring:
Extract values from objects or arrays into variables.
// Array Destructuring
let [a, b] = [1, 2];
console.log(a, b); // Output: 1 2
// Object Destructuring
let person = { name: "Krish", age: 25 };
let { name, age } = person;
console.log(name, age); // Output: Krish 25
Spread Operator:
Used to expand or merge elements/objects.
let arr1 = [1, 2];
let arr2 = [3, 4];
let merged = [...arr1, ...arr2];
console.log(merged); // Output: [1, 2, 3, 4]
let person = { name: "Krish", age: 25 };
let updatedPerson = { ...person, city: "Kathmandu" };
console.log(updatedPerson); // Output: { name: "Krish", age: 25, city: "Kathmandu" }
Promises:
A way to handle asynchronous operations.
let promise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Operation was successful");
} else {
reject("Operation failed");
}
});
promise
.then(result => console.log(result))
.catch(error => console.log(error));
11. Error Handling
Try-Catch:
Handles errors gracefully during code execution.
try {
let result = riskyFunction();
} catch (error) {
console.log("Error caught: ", error);
}
12. Conclusion
JavaScript is a powerful and versatile programming language for creating dynamic web pages and applications. From basic concepts to advanced techniques, understanding these features will help you become proficient in JavaScript.
Next Steps:
- Practice by building small projects.
- Explore the vast documentation on MDN Web Docs to dive deeper into JavaScript's capabilities.
Feel free to adapt this tutorial for your blog. You can add more examples and personal experiences to make it more engaging.
Comments
Post a Comment