Js Notes
Js Notes
Setting Up JavaScript
1. A Text Editor or IDE: Visual Studio Code, Sublime Text, Atom, etc.
2. A Web Browser: Chrome, Firefox, Edge, etc.
You can run JavaScript directly in the browser’s console or by embedding it in HTML files.
1. Inline JavaScript: Inside the <script> tag within the HTML file.
2. External JavaScript: In a separate .js file and linking it using the <script
src="path/to/file.js"></script> tag.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
1. Variables
Variables are used to store data. In JavaScript, you can declare variables using var, let, or
const.
Example:
2. Data Types
● Primitive Types:
○ String: "Hello"
○ Number: 42, 3.14
○ Boolean: true, false
○ Null: null
3. Operators
Control Structures
1. Conditional Statements
2. Loops
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
● do-while: Loops through a block of code once, and then repeats the loop while a
specified condition is true.
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
Functions
function greet(name) {
return "Hello, " + name + "!";
}
Functions can also be assigned to variables (function expressions) and created using the
arrow function syntax (ES6).
● Function Expression:
● Arrow Function:
1. Objects
const person = {
name: "Alice",
age: 30,
greet: function() {
console.log("Hello, " + this.name);
}
};
console.log(person.name);
person.greet();
2. Arrays
Events
JavaScript can respond to user actions such as clicks, mouse movements, and key presses.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Event Handling</title>
</head>
<body>
<button id="myButton">Click me</button>
<script>
document.getElementById("myButton").addEventListener("click",
function() {
alert("Button clicked!");
});
</script>
</body>
</html>
The Document Object Model (DOM) represents the structure of an HTML document.
● Selecting Elements:
● Changing Content:
● Changing Styles:
Asynchronous JavaScript
1. Callbacks
function fetchData(callback) {
setTimeout(() => {
callback("Data fetched");
}, 1000);
}
fetchData((message) => {
2. Promises
fetchData.then((message) => {
console.log(message);
});
3. Async/Await (ES8)
console.log(response);
}
fetchData();
This guide covers the basics of JavaScript. Practice by writing small programs and
experimenting with different features. Explore more advanced topics like classes, modules,
and JavaScript frameworks/libraries (e.g., React, Angular, Vue) as you become more
comfortable with the language. Happy coding!