Introduction to JavaScript
JavaScript is a versatile, high-level programming language primarily used for web
development to create dynamic and interactive content on websites. It can be used on both
the client side (in the browser) and the server side (using environments like Node.js).
Setting Up JavaScript
To start coding in JavaScript, you need:
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.
Including JavaScript in HTML
You can include JavaScript in an HTML file in two ways:
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">
© 2024 Yuvamytr. All rights reserved. 1
<title>JavaScript Example</title>
</head>
<body>
<h1>Hello, World!</h1>
<script>
console.log("This is inline JavaScript!");
</script>
<script src="script.js"></script>
</body>
</html>
Basic Syntax and Data Types
1. Variables
Variables are used to store data. In JavaScript, you can declare variables using var, let, or
const.
● var: Function-scoped variable.
● let: Block-scoped variable (introduced in ES6).
● const: Block-scoped, immutable variable (introduced in ES6).
Example:
var name = "John";
let age = 25;
const country = "USA";
2. Data Types
JavaScript has several data types:
● Primitive Types:
○ String: "Hello"
○ Number: 42, 3.14
○ Boolean: true, false
○ Null: null
© 2024 Yuvamytr. All rights reserved. 2
○ Undefined: undefined
○ Symbol (ES6): Symbol("id")
● Composite Types:
○ Object: { key: "value" }
○ Array: [1, 2, 3]
○ Function: function() { ... }
3. Operators
● Arithmetic Operators: +, -, *, /, %, ++, --
● Assignment Operators: =, +=, -=, *=, /=, %=
● Comparison Operators: ==, ===, !=, !==, >, <, >=, <=
● Logical Operators: &&, ||, !
Control Structures
1. Conditional Statements
● if-else: Executes code based on a condition.
let number = 10;
if (number > 5) {
console.log("Number is greater than 5");
} else {
console.log("Number is 5 or less");
}
● switch: Executes code based on multiple conditions.
let fruit = "apple";
switch (fruit) {
case "apple":
console.log("It's an apple");
break;
case "banana":
console.log("It's a banana");
break;
© 2024 Yuvamytr. All rights reserved. 3
default:
console.log("Unknown fruit");
}
2. Loops
● for: Loops through a block of code a number of times.
for (let i = 0; i < 5; i++) {
console.log(i);
}
● while: Loops through a block of code while a specified condition is true.
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
Functions are reusable blocks of code that perform a specific task.
function greet(name) {
return "Hello, " + name + "!";
}
© 2024 Yuvamytr. All rights reserved. 4
console.log(greet("Alice"));
Functions can also be assigned to variables (function expressions) and created using the
arrow function syntax (ES6).
● Function Expression:
const greet = function(name) {
return "Hello, " + name + "!";
};
console.log(greet("Bob"));
● Arrow Function:
const greet = (name) => "Hello, " + name + "!";
console.log(greet("Charlie"));
Objects and Arrays
1. Objects
Objects are collections of key-value pairs.
const person = {
name: "Alice",
age: 30,
greet: function() {
console.log("Hello, " + this.name);
}
};
console.log(person.name);
person.greet();
2. Arrays
© 2024 Yuvamytr. All rights reserved. 5
Arrays are ordered collections of values.
const numbers = [1, 2, 3, 4, 5];
console.log(numbers[0]); // Output: 1
numbers.push(6); // Add to the end
numbers.pop(); // Remove from the end
numbers.unshift(0); // Add to the beginning
numbers.shift(); // Remove from the beginning
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>
© 2024 Yuvamytr. All rights reserved. 6
DOM Manipulation
The Document Object Model (DOM) represents the structure of an HTML document.
● Selecting Elements:
const element = document.getElementById("myId");
const elements = document.getElementsByClassName("myClass");
const elements = document.getElementsByTagName("div");
const element = document.querySelector(".myClass");
const elements = document.querySelectorAll(".myClass");
● Changing Content:
const element = document.getElementById("myId");
element.innerHTML = "New Content";
element.textContent = "New Text";
● Changing Styles:
const element = document.getElementById("myId");
element.style.color = "red";
element.style.fontSize = "20px";
Asynchronous JavaScript
1. Callbacks
A function passed as an argument to another function to be executed later.
function fetchData(callback) {
setTimeout(() => {
callback("Data fetched");
}, 1000);
}
fetchData((message) => {
© 2024 Yuvamytr. All rights reserved. 7
console.log(message);
});
2. Promises
An object representing the eventual completion or failure of an asynchronous operation.
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data fetched");
}, 1000);
});
fetchData.then((message) => {
console.log(message);
});
3. Async/Await (ES8)
Syntax for writing asynchronous code in a synchronous manner.
async function fetchData() {
const response = await new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data fetched");
}, 1000);
});
console.log(response);
}
fetchData();
© 2024 Yuvamytr. All rights reserved. 8
Conclusion
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!
© 2024 Yuvamytr. All rights reserved. 9