JavaScript is a powerful and flexible programming language for the web that is widely used to make websites interactive and dynamic. JavaScript can also able to change or update HTML and CSS dynamically. JavaScript can also run on servers using tools like Node.js, allowing developers to build entire applications with it.
What is JavaScriptIn this tutorial we will see some of the important concepts to start with JavaScript
JavaScript Variables
JavaScript variables are containers for storing data in memory, allowing you to reference and manipulate it. They can be declared using var
, let
, or const
, each with different scoping and usage rules.
JavaScript
let a = [ 1, 2, 3 ]; // Array
const s = "Hello"; // String
var n = 42; // Number
console.log(a);
console.log(s);
console.log(n);
Output[ 1, 2, 3 ]
Hello
42
Data Types
JavaScript includes primitive data types such as Number
, String
, Boolean
, Null
, Undefined
, and Symbol
. It also has non-primitive data types like Array
, Object
, and Function
. Primitive types are passed by value, meaning changes to a copied value do not affect the original. Non-primitive types are passed by reference, meaning changes to the reference affect the original object.
JavaScript
let n = 10; // number
let s = "Hello GFG"; // string
let b = true; // boolean
let f = function() { console.log("Hello GFG"); } // function
let arr = [ 1, 2, 3, 4, 5 ];
let obj = {name : "GFG"}
console.log(typeof n);
console.log(typeof s);
console.log(typeof b);
console.log(typeof f);
console.log(typeof arr); // in javascript arrays are also objects
console.log(typeof obj);
Outputnumber
string
boolean
function
object
object
Functions
Functions in JavaScript are reusable blocks of code designed to perform a specific task. They help organize and simplify code by allowing you to call the same logic multiple times.
JavaScript
function add(x, y) {
return x + y;
}
console.log(add(5, 7));
Control Statements
Control structures in JavaScript handle decision-making with conditions and repeat tasks using loops. They help control the flow of your code based on logic.
JavaScript
let n = 41;
if (n > 40) {
console.log("n is large");
}
else {
console.log("n is small");
}
let a = [ 1, 2, 3 ];
for (let i = 0; i < a.length; i++) {
console.log(a[i]);
}
Objects
Objects in JavaScript are collections of key-value pairs used to store related data. They work by reference, meaning changes to the reference affect the original object.
JavaScript
const obj = { name: "Manoj", age: 25 };
console.log(obj.name);
Arrays
Arrays in JavaScript are used to store multiple items in a single list. You can access each item using its position, called an index. Arrays in JavaScript can hold different types of data, such as numbers, strings, or even other arrays
JavaScript
const a = [10, 20, 30];
a.push(40);
console.log(a);
Events
Events in JavaScript are actions that happen in the browser, like a button click or a mouse move. You can use JavaScript to respond to these events and trigger specific actions.
HTML
<html>
<body>
<button id="bn">Click me to get a alert</button>
<script>
let btn = document.getElementById('bn');
btn.onclick = function () {
alert("You have clicked me");
}
</script>
</body>
</html>
Promises
Promises are a way of handling asynchronous tasks in JavaScript. They are commonly used for tasks like data fetching and other operations that require waiting for a result, and they have three states: pending, fulfilled, and rejected.
JavaScript
let promise = new Promise((resolve, reject) => {
let s = "HELLO GFG";
if (s) {
resolve(s);
}
else {
reject("Some error Occured");
}
}
)
promise.then((data) =>
console.log(data)).catch((error) =>
console.log(error));
Arrow Functions
Arrow functions are a shorthand syntax for writing functions in JavaScript, using the =>
operator. They offer a more concise way to express functions, especially for single-expression functions.
JavaScript
let add = (a, b) => {
return a + b;
}
console.log(add(2, 3));
DOM Manipulation
DOM manipulation refers to the process of changing the structure, content, or style of HTML elements using JavaScript. It allows dynamic updates to a webpage without reloading the entire page.
HTML
<html>
<head>
<style>
#bn{
position: relative;
left: 50vw;
top: 100px;
}
.background{
background-color:chocolate;
}
</style>
</head>
<body>
<button id="bn">Click me to get a alert</button>
<script>
let btn=document.getElementById('bn');
btn.onclick=function(){
document.body.classList.toggle('background');
}
</script>
</body>
</html>
Classes in JavaScript
A class is like a recipe for making objects. It tells you what ingredients (properties) and steps (actions) are needed to make something, and you can use the same recipe to make many objects that work the same way.
JavaScript
class GFG {
constructor(name) { this.name = name; }
}
const a = new GFG("GEEKS FOR GEEKS");
console.log(a.name);
Error Handling
Error handling is the process of catching and managing errors in code to prevent crashes. It allows the program to continue running smoothly even when something goes wrong.
JavaScript
try {
let a = 10 / 0;
if (a === Infinity) {
throw new Error("Can not divide by zero");
}
console.log(a)
}
catch (err) {
console.log(err.message);
}
OutputCan not divide by zero
Dynamic Behavior of JavaScript
In JavaScript, server-side behavior involves running code on the server (like with Node.js) to process requests and generate dynamic content. Client-side behavior happens in the browser, where JavaScript interacts with HTML and CSS to make the webpage interactive. JavaScript can handle both sides, sending and receiving data between the server and client for a seamless experience.
Synchronus Behavior of JavaScript
In JavaScript, synchronous behavior means tasks are executed line by line, blocking the program's flow until the task is completed. This means the code has to wait for one operation to finish before moving on to the next one. It’s used for operations that don't depend on asynchronous events, like simple calculations or data processing.
JavaScript
// Function that simulates an asynchronous operation using setTimeout
function delay() {
console.log("Greeting will be displayed after 2 seconds...");
setTimeout(() => {
console.log("Hello, after 2 seconds!");
}, 2000);
}
delay();
console.log("This is displayed immediately.");
defer and async in JavaScript
In JavaScript, defer
and async
are used to control the loading of external scripts. defer
ensures the script is executed after the HTML is fully parsed, preserving the order of execution. async
runs the script as soon as it's downloaded, without waiting for the HTML to finish parsing, which can disrupt the order.
Similar Reads
What is HTML?
HTML (HyperText Markup Language) is the standard markup language used to structure and design web pages. It defines how text, images, and multimedia content are displayed in a web browser. HTML uses tags and elements to organize content on a webpage.It was created by Tim Berners-Lee in 1990 for shar
4 min read
What is CSS?
CSS, which stands for Cascading Style Sheets is a language in web development that enhances the presentation of HTML elements. By applying styles like color, layout, and spacing, CSS makes web pages visually appealing and responsive to various screen sizes. CSS allows you to control the look and fee
5 min read
What is JavaScript?
JavaScript is a powerful and flexible programming language for the web that is widely used to make websites interactive and dynamic. JavaScript can also able to change or update HTML and CSS dynamically. JavaScript can also run on servers using tools like Node.js, allowing developers to build entire
6 min read
What is JSON?
JSON (JavaScript Object Notation) is a lightweight text-based format for storing and exchanging data. It is easy to read, write, and widely used for communication between a server and a client. Key points:JSON stores data in key-value pairs.It is language-independent but derived from JavaScript synt
3 min read
What is NPM & How to use it ?
NPM, short for Node Package Manager, is the default package manager for NodeJS. It is a command-line utility that allows you to install, manage, and share packages or modules of JavaScript code. These packages can range from small utility libraries to large frameworks, and they can be easily integra
3 min read
What is React?
React JS is a free library for making websites look and feel cool. It's like a special helper for JavaScript. People from Facebook and other communities work together to keep it awesome and up-to-date. React is Developed by Facebook, React is a powerful JavaScript library used for building user inte
6 min read
What is React Router?
React Router is like a traffic controller for your React application. Just like how a traffic controller directs vehicles on roads, React Router directs users to different parts of your app based on the URL they visit. So, when you click on a link or type a URL in your browser, React Router decides
2 min read
What is Material UI ?
Material UI is a popular React UI framework that provides pre-designed components following Google's Material Design guidelines. It simplifies the process of creating sleek and responsive user interfaces by offering a library of customizable components. Default Installationnpm install @mui/material
1 min read
What is Node?
Node is a JavaScript runtime environment that enables the execution of code on the server side. It allows developers to execute JavaScript code outside of a web browser, enabling the development of scalable and efficient network applications. Table of Content What is Node?Steps to setup the Node App
3 min read
What is Express?
Express is a minimal and flexible web application framework for NodeJS. It provides a robust set of features for building dynamic web applications and APIs, making it one of the most popular frameworks used in the development of web applications on the server side. Simplifies routing and middleware
5 min read