Learn JavaScript Basics to Advance
Anish Khadtare
Posted on October 15, 2023
JavaScript is a versatile and dynamic programming language that has become a fundamental tool in modern web development. Initially designed to add interactivity to web pages, JavaScript has evolved to become a robust language used for creating complex applications and running code on various platforms. Whether you want to enhance user interfaces, build server-side applications, or develop mobile applications, JavaScript provides the foundation for all these endeavors.
We would start from the basics and explore the advanced topics too. Let's get started.
BASICS
Variables in JavaScript
In JavaScript, three variables are used to declare variables var, let, and const.
var car = 'Tata Nexon';
let colour = 'Blue';
const carId = 509;
var is functionally scoped when declared inside a function and global scope when declared outside a function. The value of the variable declared by var can be changed and re-declared.
A block is a piece of code inside {}. Anything written inside the curly braces is a block. A variable declared in a block with let is only available for use within that block. So the value of that variable can not be accessed outside the block. The value of let can be changed but not re-declared.
const is used to declare some constant value that will not be changed at any time. The value of the const variable can not be changed nor re-declared.
Data Types in JavaScript
JavaScript has several data types, including numbers, strings, booleans, arrays, and objects.
let age = 20;
let language = 'JavaScript';
let flag = true;
let array = [10,20,30,40,50];
let code = {lines : 100, errors : 0, topic : 'blog'};
Arrays in JavaScript
Arrays consist of square brackets and items that are separated by commas.
let fruits = ["Mango","Apples","Oranges","Guava"];
console.log(fruits);
let random = [52,"laptop","grapes",67];
console.log(random);
let number = [52,83,12,64,67];
console.log(number);
/*Finding length of array*/
console.log(fruits.lenght);
/*Accessing a particular element from an array*/
console.log(fruits[2]);
/*Adding items to end of array */
random.push(16);
/*Removing items from end of array */
random.pop(16);
/*Adding items to start of array */
random.unshift(16);
/*Removing items from start of array */
random.shift(16);
/* Accessing all the elements of array using map */
/* Here for every num in array number each num is doubled */
let doubled = number.map((num) => num*2);
console.log(doubled);
/* Filtering the array */
Objects in JavaScript
An object is a collection of several properties and functions that belong to a particular object.
The object is made in the key-value pair format.
const car = {
color:"white",
brand:"Tata",
price:500000,
information: function(){
console.log(`The car is of colour ${color}`);
};
Here the car is the object having a color, brand, price, information are keys.
Operators in JavaScript
JavaScript supports arithmetic, assignment, comparison, logical, and other operators.
let x = 15 + 5; // Addition
let y = 16 - 5; // Subtraction
let z = 6 * 5; // Multiplication
let w = 20 / 5; // Division
let a = 50 % 5; // Modulo
let b = 10;
b += 15; // b is now 15 (addition assignment)
let isEqual = (50 === 15); // Comparison (equal to)
let result = (x > 0 && y < 5); // Logical (AND)
Control Flow in JavaScript
JavaScript provides control flow statements like if-else, for loops, and while loops.
let num = 10;
if (num > 0) { /* Checks the condition */
console.log('Number is positive');
}
else if (num < 0) { /* If the first condition not statisfied */
console.log('Number is negative');
}
else { /* If no condition are statisfied */
console.log('Number is zero');
}
for (let i = 0; i < 5; i++) { /* For Loop */
console.log(i);
}
let i = 0; /* While loop */
while (i < 5) {
console.log(i);
i++;
}
Functions in JavaScript
JavaScript functions allow you to group code into reusable blocks.
function carProperties(colour,price){
console.log("Car is of " + colour + " colour and its price is " + price + " Rs ");
}
carProperties("white",500000);
Here carProperties is the function name having parameters color and price of the car. The value of these parameters is given in the function call as white and 500000.
Now this same function can be written in a simpler way or an optimized way which is the ARROW Function.
const carProperties = (colour,price) => {
console.log("Car is of " + colour + " colour and its price is " + price + " Rs ");
}
carProperties("white",500000);
Intermediate
this keyword
this keyword is a special type of keyword that refers to the context in which a function is executed. It allows to access properties and methods within the current execution context.
const cars = {
colour : "blue",
price : 500000,
brand : "Tata Nexon",
info : function(){
return this.brand + " " + this.colour + " " + this.price;
}
}
Here this keyword refers to the parent object cars.
When this keyword is used alone it refers to a global object.
let value = this;
console.log(value);
Async Functions in JavaScript
Async functions are a feature in JavaScript that allows you to write asynchronous code in a more synchronous-like manner. They are defined using the async keyword, and they always return a promise. The use of async functions is closely tied to the await keyword, which can be used to pause the execution of the function until a promise is resolved. Async Functions are used while fetching data from APIs.
async function fetchData(){
try{
const response = await fetch("https://api.info/cars"); /* Your API */
const data = await response.json();
console.log(data);
}
catch(error){
console.log("ERROR : ",error);
}
}
The function fetchData is an asynchronous function and error handling is performed using try and catch. The data is fetched from the API using the fetch keyword and stored in response. The await keyword is used to pause the execution until a promise is resolved. This response is then parsed in the response body as JSON.
CallBack functions in JavaScript
The callback function is a function that is passed within a function as a parameter and is invoked inside the function.
function fetchData(callback) {
setTimeout(function() {
const data = { id: 1, name: 'John Doe' };
callback(null, data);
}, 2000);
}
function processResult(error, data) {
if (error) {
console.log('Error:', error);
} else {
console.log('Data:', data);
}
}
fetchData(processResult);
Advanced
getElementById in JavaScript
The getElementById is used to manipulate the HTML elements on a web page by using the unique ID given to them.
<html>
<head> </head>
<body>
<p id="score">0</p>
</body>
<script src="script.js"></script>
</html>
let value = 10;
let score = document.getElementById("score");
/* Now for changing the contents */
score.innerText = value;
So here the HTML element is been accessed using the ID score and then manipulated using innerText to change the value of the score to 10 on the web page.
Similarly for accessing elements by classes, we can use getElementsByClassName.
Accessing elements can also be done using querySelector("#id") and querySelectorAll(".className").
addEventListner in JavaScript
In JavaScript, the addEventListners method is used to attach event handlers to HTML elements. This method allows you to define a function that will be executed when a specific event occurs on the target element.
const btn = document.getElementById("button");
btn.addEventListner("click",()=> {
console.log("clicked Button");
})
forEach in JavaScript
When we want to perform the same action many times, instead of using it every time we can perform the same action a single time for different objects.
<html>
<head> </head>
<body>
<p id="count">0</p>
<button class="btn btnInc">Increase</button>
<button class="btn btnRes">Reset</button>
<button class="btn btnDec">Decrease</button>
</body>
<script src="script.js"></script>
</html>
const btns = document.querySelectorAll(".btn");
let count = document.getElementById("count");
let value = 0;
btns.forEach((btn) => {
if(btn.currentTarget.classList.contains("btnInc")){
value++;
}
else if(btn.currentTarget.classList.contains("btnDec")){
value--;
}
else{
value = 0;
}
})
count.innerText = value;
map in Javascript
In JavaScript, the map method is used to transform the elements of an array by applying a given function to each element and creating a new array with the results. It is a common functional programming method that is often used for tasks like data manipulation, filtering, or extracting specific values from an array.
const numbers = [1, 2, 3, 4, 5];
// Doubling each number using map
const doubledNumbers = numbers.map((number) => {
return number * 2;
});
console.log(doubledNumbers);
filter in javaScript
In JavaScript, the filter method is used to create a new array containing all the elements from an existing array that meet a specified condition. It's a convenient way to filter out elements that you don't need from an array.
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Filtering even numbers using filter
const evenNumbers = numbers.filter((number) => {
return number % 2 === 0;
});
console.log(evenNumbers); // Output: [2, 4, 6, 8, 10]
Posted on October 15, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.