JavaScript is a programming language that is commonly used to add interactivity to websites. Here are some fundamental concepts of JavaScript:
1. Functions: Functions are blocks of code that can be called by name. They are often used to perform a specific task or to abstract away complex code.
function sayHello() {
console.log("Hello!");
}
sayHello(); // prints "Hello!" to the console
Functions can also accept parameters and return values:
function add(x, y) {
return x + y;
}
var result = add(10, 20); // result is 30
2. Objects: Objects are data structures that contain properties and methods. Properties are values associated with an object, and methods are functions that belong to an object.
Here’s an example of an object that represents a person:
var person = {
name: "John",
age: 30,
sayHello: function() {
console.log("Hello, my name is " + this.name);
}
};
console.log(person.name); // prints "John"
console.log(person.age); // prints 30
person.sayHello(); // prints "Hello, my name is John"
3. Arrays: Arrays are used to store lists of data. They are declared using square brackets, and the elements are separated by commas.
var numbers = [1, 2, 3, 4, 5];
console.log(numbers[0]); // prints 1
console.log(numbers[4]); // prints 5
for (var i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
4. Events: Events are actions that can be detected by JavaScript code. For example, a user clicking a button is an event. You can use event listeners to specify code that should be executed when a particular event occurs.
Here’s an example of a button that displays an alert when it is clicked:
<button id="myButton">Click me</button>
<script>
var button = document.getElementById("myButton");
button.addEventListener("click", function() {
alert("Button was clicked!");
});
</script>
5. Class-based inheritance: JavaScript is an object-oriented programming language, which means that you can use classes to define objects. A class is a template for creating objects, and an object is an instance of a class.
Here’s an example of a class that defines a Person
object:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHello() {
console.log("Hello, my name is " + this.name);
}
}
var john = new Person("Swapnil", 30);
console.log(john.name); // prints "Swapnil"
console.log(john.age); // prints 30
john.sayHello(); // prints "Hello, my name is Swapnil"
In this example, the Person
class has a constructor
method that is used to initialize the object’s properties, and a sayHello
method that is used to greet the person.
You can also use inheritance to create a new class that is based on an existing class. For example:
class Student extends Person {
constructor(name, age, major) {
super(name, age);
this.major = major;
}
sayHello() {
super.sayHello();
console.log("I'm studying " + this.major);
}
}
var jane = new Student("Swapnil", 20, "Computer Science");
jane.sayHello(); // prints "Hello, my name is Swapnil. I'm studying Computer Science"
In this example, the Student
class extends the Person
class and adds a major
property and a modified sayHello
method. The super
keyword is used to call the parent class’s methods.
6. Asynchronous programming: JavaScript is an event-driven language, which means that your code can execute asynchronously. This is often used when working with network requests, timers, and other tasks that may take some time to complete.
Here’s an example of using the setTimeout
function to delay the execution of a function:
function sayHello() {
console.log("Hello!");
}
setTimeout(sayHello, 1000); // prints "Hello!" after 1 second
You can also use the async
and await
keywords to write asynchronous code in a more synchronous-looking style. For example:
async function getData() {
let response = await fetch("https://api.example.com/endpoint");
let data = await response.json();
console.log(data);
}
getData(); // logs the data from the API endpoint
In this example, the getData
function uses the fetch
function to make a network request and then waits for the response to be received before parsing the data and logging it to the console.
7. Promises: Promises are a way to handle asynchronous code in JavaScript. They represent a value that may be available in the future, either a resolved value or a reason why the value is not available. Promises can be used to simplify asynchronous code and avoid the use of callback functions.
Here’s an example of using a promise to wrap a timer function:
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
delay(1000)
.then(() => {
console.log("1 second has passed");
});
Promises can also be used to chain asynchronous actions together:
function getData() {
return fetch("https://api.example.com/endpoint")
.then(response => response.json());
}
getData()
.then(data => {
console.log(data);
});
In this example, the getData
function returns a promise that is resolved with the data from the API endpoint. The then
method is used to specify what should happen when the promise is resolved.
8. Modules: Modules are a way to organize and reuse code in JavaScript. A module is a script that is executed in its own scope, which means that variables and functions defined in the module are not visible to the global scope. Modules can export values, which can be imported by other scripts.
Here’s an example of a module that exports a function:
// greet.js
export function sayHello(name) {
console.log("Hello, " + name);
}
To use the module, you can import it in another script:
// main.js
import { sayHello } from "./greet.js";
sayHello("John"); // prints "Hello, John"
Modules can also export default values, which can be imported without specifying the name:
// greet.js
export default function(name) {
console.log("Hello, " + name);
}
// main.js
import greet from "./greet.js";
greet("John"); // prints "Hello, John"