Top Basic Javascript Concepts (Part-1)
Variables: Variables are containers for storing data values. There are three types of variables in JavaScript: var, let, and const.
let x = 5; // x is 5
const pi = 3.14; // pi is a constant 3.14
Data Types: JavaScript has several data types including Number, String, Boolean, Object, Function, Null, and Undefined.
let number = 5; // Number
let string = "Hello"; // String
Arrays: Arrays are used to store multiple values in a single variable.
let fruits » ["apple", "banana", "cherry"];
Objects: Objects are variables too. But objects can contain many values.
let car = {type: "Fiat", model: "500", color: "white"};
Operators: JavaScript includes arithmetic operators, comparison operators, bitwise operators, logical operators, assignment operators, etc.
let x = 5;
let y = x + 2; // y is now 7
Control Structures: Control structures help you handle the flow of your program. This includes if, else, switch, for, while, do-while.
if (x > y) {
// do something
} else {
// do something else
}
Functions: Functions are blocks of code that can be defined, then called at a later time, or in response to an event.
function myFunction(x, y) {
return x * y;
}
Events: JavaScript's interaction with HTML is handled through events that occur when the user or browser manipulates a page.
<button onclick="myFunction()">Click me</button>
Strings and String Methods: Strings are useful for holding data that can be represented in text form. There are many methods that can be used with strings including length, index0f, search, replace, etc.
let txt = "Hello World!";
let x = txt.length; // x is now 12
Number and Number Methods: JavaScript has only one type of number. Numbers can be written with, or without decimals. JavaScript numbers can also include + and, and e to indicate exponents.
let x = 123e5; // x is 12300000
let y 123e-5; // y is 0.00123
Dates: JavaScript Date objects represent a single moment in time in a platform-independent format. Date objects contain a Number that represents milliseconds passed since the Unix Epoch.
let d = new Date();
JavaScript Math: JavaScript Math is a built-in object that has properties and methods for mathematical constants and functions.
console.log(Math.PI); // 3.141592653589793
console.log(Math.sqrt(16)); // 4
Boolean Logic: Boolean is a datatype that returns either of two values i.e., true or false.
let isCodingFun = true;
let isFishTasty = false;
Error Handling (try/catch/finally): JavaScript allows exception handling via the try, catch, and finally blocks. try contains the code to be run, catch catches any errors, and finally runs code regardless of an error occurring or not.
try {
notAFunction();
} catch(err) {
console.log(err); // ReferenceError: notAFunction is not defined
} finally {
console.log('This will run regardless of the try/catch result');
}
Regular Expressions: Regular expression is an object that describes a pattern of characters.
let patt = new RegExp("e");
let res = patt.test("The best things in life are free!");
JSON: JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate.
let text = "{"name":"John", "birth":"1986-12-14", "city": "New York"}';
let obj = JSON.parse(text);
AJAX: AJAX is about updating parts of a web page, without reloading the whole page. It stands for Asynchronous JavaScript and XML.
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState ==4&& this.status == 200) {
// Typical action to be performed when the document is ready document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open
("GET", "filename", true); xhttp.send();
Promises: A Promise is an object representing the eventual completion or failure of an asynchronous operation.
let promise = new Promise(function(resolve, reject) {
// do a thing, possibly async, then...
if (/* everything turned out fine */) {
resolve("Stuff worked!");
} else {
reject (Error("It broke"));
}
});
Async/Await: async and await make promises easier to write.
async function example() {
let response = await fetch('
https://api.github.com/users/github
');
let user= await response.json();
return user;
}
Closures: A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment).
function makeAdder (x) {
return function (y) {
return x + y;
};
}
let add5 makeAdder (5);
let add10 makeAdder(10);
console.log(add5(2)); // 7
console.log(add10(2)); // 12
Arrow Functions: Arrow functions allow for a shorter syntax when writing functions. Arrow functions do not have their own this.
const square = x => x * x;
Template Literals: Template literals provide an easy way to interpolate variables and expressions into strings.
let name="John";
console.log("Hello, ${name}!'); // "Hello, John!"
Spread Operator and Rest Parameters: The spread operator allows an iterable to be expanded in places where zero or more arguments are expected. The rest parameter syntax allows a function to accept an indefinite number of arguments as an array.
// Spread operator
let arr1 [1, 2, 3];
let arr2= [...arr1, 4, 5, 6]; // [1, 2, 3, 4, 5, 6]
// Rest parameters
function sum(... theArgs) {
return theArgs.reduce((previous, current) => {
return previous + current;
});
}
Subscribe to my newsletter
Read articles from Keshav Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Keshav Kumar
Keshav Kumar
Tech Writer | Open Source