// Variable declaration //automatically a_ = 5; b_ = 6; c_ = a_ + b_; console.log(c_); // let , var , const let a; var b; const c = 3.14; a = 5; b = 4; b = 6; z = a + b + c; console.log(z); //var var x = "om"; var x = 0; console.log(x); x = 5; console.log(x); var x = 8; { var x = 10; } console.log(x); //Hoisting but not with let or const : ReferenceError carName = 'bmw'; var carName; console.log(carName); //let let x1 = "om"; //let x1 = 0; error not redeclared x1 = "hari"; console.log(x1); let x2 = 2; { let x2 = 10; } console.log(x2); //const const PI = 3.14; console.log(PI); //Arrays const cars = ['audi', 'bmw', 'volvo']; cars[0] = 'tata'; //change an element cars.push('fortunar'); //add an element /* but cannot reassign : TypeError cars = ['thar', 'jaguar']; */ console.log(cars); console.log(typeof(cars)); //Objects const car = {name : 'bmw', color : 'white', year : 2023}; car.color = 'black'; //change properties car.owner = 'hariom'; //add properties /* but cannot reassign by using const & let : TypeError car = {name : 'audi',color:'black'}; */ console.log(car); console.log(typeof(car)); var car1 = {name : 'audi', color : 'red'}; console.log(car1); var car1 = {name : 'bmw', color : 'white'}; console.log(car1); console.log(car1.name); const person = { fname : 'hari', lname : 'om', fullname : function(){ return this.fname + ' ' + this.lname; } } // String, Number, Boolean as Objects o1_ = new String(); o2_ = new Number(); o3_ = new Boolean(); //Operations // String Comparison let s1 = 'ba'; let s2 = 'c'; let s3 = 'b'; let s4 = '5'; let s5 = '4'; let s6 = 8; let s7 = 'caa'; console.log(s1 < s2); console.log(s2 < s3); console.log(s3 < s4); console.log(s4 < s5); console.log(s5 < s6); console.log(s1 < s7); console.log(typeof(s1)); console.log(typeof(s6)); let str = ' this is a string. '; console.log(str.length); let text = "Apple, Banana, Kiwi"; console.log(text.slice(7)); console.log(text.slice(7,13)); console.log(text.slice(-12)); console.log(text.slice(-12,-6)); console.log(text.substring(7)); console.log(text.substring(7,13)); console.log(text.substring(-12)); //substr(start, length) console.log(text.substr(7, 6)); console.log(text.replace('Kiwi', 'Orange')); //String to Array console.log(text.split(',')); //Template Literals let txt = `Hello back-ticks`; console.log(txt); //Interpolation & Variable substitutions let fn = 'hari'; let ln = 'om'; let full = `${fn} ${ln}`; console.log(full); let xx = "100"; let yy = "10"; let zz = xx / yy; console.log(typeof(zz)); let ss = zz.toString(); console.log(typeof(ss)); let nn = parseInt(ss); console.log(typeof(nn)); let m = 'om'; let n = new String('om'); console.log(m == n); console.log(m === n); // object compare with object gives always false let bo = true; console.log(typeof(bo)); const date = new Date("2023-07-12"); console.log(date); let xs = 'bmw' + 16 + 4; console.log(xs); let sx = 16 + 4 + 'bmw'; console.log(sx); let un; console.log(un); console.log(typeof(un)); let bike = ''; //empty String let arr = []; //empty Arrays arr[0] = 'tvs'; arr[1] = 'honda'; console.log(arr); // array to String let na = arr.toString(); console.log(na); //using objects const ccc = new Array("Saab", "Volvo", "BMW"); let obj = {}; //empty Objects // Array map() creates new array by performing a Functions //on each array element const num1 = [45, 4, 9, 16, 25]; const num2 = num1.map(funct); function funct(value, index, array) { return value * 2; } console.log(num2); //Normal Functions function add(a,b){ console.log(a+b); } add(3,4); let xfm = multip(5,8); console.log(xfm); function multip(a,b){ return (a*b); } //Arrow Function let addi = (a,b) => a + b; const ans = addi(4,7); console.log(ans); //Simple arrow hello = () => console.log("hello"); hello(); //Function Expression const exp = function(a,b){ return a*b; } let ex = exp(6,8); console.log(ex); //Function Constructor const cons = new Function("a", "b", "return a * b"); console.log(typeof(cons)); let fc = cons(4, 3); console.log(fc); console.log(typeof(fc)); // Function Hoisting let fh = myFu(5); console.log(fh); function myFu(y) { return y * y; } //Self - Invoking Functions (function(){ console.log("Self invoking"); })(); /* call & apply(args = array) method const person = { fullName: function() { return this.firstName + " " + this.lastName; } } const person1 = { firstName:"John", lastName: "Doe" } const person2 = { firstName:"Mary", lastName: "Doe" } person.fullName.call(person1); const per = { fullName: function(city, country) { return this.firstName + " " + this.lastName + "," + city + "," + country; } } const per1 = { firstName:"Hari", lastName: "Om" } per.fullName.apply(per1, ["lko", "India"]); */ // object Constructor function Person(first, last, age, eye) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eye; } const myFather = new Person("John", "Doe", 50, "blue"); const myMother = new Person("Sally", "Rally", 48, "green"); //for...of const arry = [1,2,3]; for(const j of arry){ console.log(j); } //for...in const pn = {firstName:"John", lastName:"Doe", age:50}; let s = ''; let ar = []; //property print for(let i in pn){ console.log(i); ar.push(i); } console.log(ar); //values print for(let i in pn){ s += pn[i] + ' '; ar.push(pn[i]); } console.log(ar); console.log(s); pn.color = "black"; console.log(pn); //forEach() /* const letters = new Set(["a","b","c"]); let text = ""; letters.forEach (function(value) { text += value; }) */ const newarr = new Array('a','b','c'); let news = ''; newarr.forEach(function(val){ news += val; }) console.log(news); //Comparison let a8 = 10; let b8 = "10"; console.log(a8==b8); console.log(a8===b8); let o1 = {a:1, b:2, c:3}; let o2 = {a:1, b:2, c:3}; console.log(o1==o2); console.log(o1===o2); const man = { firstName: "John", lastName : "Doe", id : 5566, fullName : function() { return this.firstName + " " + this.lastName; } }; console.log(man); myObj = { name:"om", age:21, cars: { c1:"Ford", c2:"BMW", c3:"Fiat" } } console.log(myObj); console.log(myObj.cars.c2); let x8 = "John"; let y8 = new String("John"); console.log(x8==y8); let x11 = "John"; let x21 = new String("John"); console.log(x11===x21); // Template String let firstName = "John"; let lastName = "Doe"; let tt = `Welcome ${firstName}, ${lastName}!`; console.log(tt); let x3 = 10; let y2 = 20; let z2 = "30"; let rt = x3 + y2 + z2; console.log(rt); // *,-,/ also but not + concat.. let xx1 = "100"; let yy1 = "10"; let z11 = xx1 / yy1; console.log(z11); //NaN let x4 = 100 / "Apple"; console.log(x4); //Functions var cc = "Tata"; function myFunction() { let carName = "Volvo"; console.log(carName); console.log(cc); } myFunction(); //console.log(carName); console.log(cc); myFunc(); console.log(car_); function myFunc() { car_ = "BMW"; } function toc(f) { return (5/9) * (f-32); } let v = toc(77); console.log(v); //func expression var f = function(){ console.log("function expression") } f(); function add(a,b){ console.log(a+b); } add(4,5); //Arrow Function let arrFunc = (a, b) => a * b; var ans1 = arrFunc(2,3); console.log(ans1); hello = () => { console.log("Hello World!"); } hello(); //Function Hoisting multi(5); function multi(y) { console.log(y * y); } //Self-invoking function - function without name (function () { console.log("I will invoke myself"); })(); // Scope & Hoisting x5 = "Audi"; //let x5; var x5; var x5 = "Tata" //const x5; console.log(x5); /* const PI; PI = 3.14; console.log(PI); */ //spread operator let a1 = [1,2,3]; let a2 = [...a1]; console.log(a1); console.log(a2); console.log(a1==a2); console.log(a1===a2); a1.push(4); a1.unshift(0); console.log(a1); console.log(a2); a1.shift(); a1.pop(); console.log(a1); console.log(a2); const myVehicle = { brand: 'Ford', model: 'Mustang', color: 'red' } const updateMyVehicle = { type: 'car', year: 2021, color: 'yellow' } //color is overwritten const myUpdatedVehicle = {...myVehicle, ...updateMyVehicle} console.log(myUpdatedVehicle); //rest - treats arguments as an array function sum(...args) { let tsum = 0; for (const i of args) { tsum += i; } return tsum; } console.log(sum(1, 2, 3)); console.log(sum(1, 2, 3, 4)); //Closures function out(){ let a3 = 7; function inf(){ a3 = 4; console.log(a3); } inf(); console.log(a3); } out(); // Destructuring const item = ['a','b','c']; const [m11,n11,o11] = item; console.log(m11); let per = {name: "om", age:"21"}; let {name, age} = per; console.log(name); console.log(per.name); console.log(per); delete per.age; console.log(per); //Exception Handling let g = 4; try{ g = h + 1; console.log(g); } catch(err){ console.log("Error" + ': ' + err.name); } finally{ console.log("Exception"); } //Normal myCalculator function display(res){ //res = 6 return res; } function calculate(a,b){ let cs = 0; cs = a + b; return cs; } let output = calculate(9,3); //let out_ = display(output); //output = 6 console.log(output); //callback function myCalculator(num1, num2, callback) { let sum = 0; sum = num1 + num2; callback(sum); } myCalculator(5, 8, result); //as an argument function result(some) { //a callback function console.log(some); } //wrong : myCalculator(5, 8, result()); //In real world, callbacks are used with //asynchronous Functions eg.- setTimeout() /* const main = (callback) => { setTimeout(() =>{ callback([1,2,3]) //callback function },1000) } const add = (arr) =>{ let sum = 0; for(let j of arr){ sum += j; } console.log(sum); } main(add); //argument */ //callbacks for addition of an array element const mainfunc = (callback) =>{ setTimeout(() =>{ callback([1,2,3,4]) }, 1000) } const addarr = (_arr) =>{ let arrsum = 0; for(const j of _arr){ arrsum += j; } console.log(arrsum); } mainfunc(addarr); //calling main function /*callback ***** const mainfunc = (callback) =>{ setTimeout(() => { callback([1]); setTimeout(() => { callback([2]) }, 1000) }, 1000) } */ /*Promises let promise = new Promise(function(resolve, reject){ resolve(); //Success reject(); //Error }); promise.then( function(value); function(error); ); */ let mypro = new Promise(function(resolve, reject){ let r = 10; //Producing Code if(r == true){ resolve("Success"); }else{ reject("Error"); } }); mypro.then( function(value){ dis(value); }, ) .catch( function(error){ dis(error); } ); function dis(some){ console.log(some); } //separator operator but not used at start or end const sep1 = 1_000_000_000; const sep2 = 1000000000; console.log(sep1 === sep2); //Symbol let sym = Symbol("hello"); console.log(sym); let sim = Symbol("id") == Symbol("id"); console.log(sim); let cdm = "hello"; console.log(sym == cdm); console.log(Array.from("ABCDEFG")); //Default Parameter function defpara(x, y=10) { // y is 10 if not passed or undefined console.log(x + y); } defpara(5); let $1 = 1 + 1; let $2 = 2; console.log($1 == $2); let $3 = 1.1 + 0.2; let $4 = 1.3; console.log($3 == $4); //Time interval method function fun(){ for(let i=1; i<=5; i++){ setTimeout(function() { console.log(i); }, 1000); } console.log("JavaScript"); } fun();
Write, Run & Share Javascript code online using OneCompiler's JS online compiler for free. It's one of the robust, feature-rich online compilers for Javascript language. Getting started with the OneCompiler's Javascript editor is easy and fast. The editor shows sample boilerplate code when you choose language as Javascript and start coding.
Javascript(JS) is a object-oriented programming language which adhere to ECMA Script Standards. Javascript is required to design the behaviour of the web pages.
var readline = require('readline');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
rl.on('line', function(line){
console.log("Hello, " + line);
});
Keyword | Description | Scope |
---|---|---|
var | Var is used to declare variables(old way of declaring variables) | Function or global scope |
let | let is also used to declare variables(new way) | Global or block Scope |
const | const is used to declare const values. Once the value is assigned, it can not be modified | Global or block Scope |
let greetings = `Hello ${name}`
const msg = `
hello
world!
`
An array is a collection of items or values.
let arrayName = [value1, value2,..etc];
// or
let arrayName = new Array("value1","value2",..etc);
let mobiles = ["iPhone", "Samsung", "Pixel"];
// accessing an array
console.log(mobiles[0]);
// changing an array element
mobiles[3] = "Nokia";
Arrow Functions helps developers to write code in concise way, it’s introduced in ES6.
Arrow functions can be written in multiple ways. Below are couple of ways to use arrow function but it can be written in many other ways as well.
() => expression
const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
const squaresOfEvenNumbers = numbers.filter(ele => ele % 2 == 0)
.map(ele => ele ** 2);
console.log(squaresOfEvenNumbers);
let [firstName, lastName] = ['Foo', 'Bar']
let {firstName, lastName} = {
firstName: 'Foo',
lastName: 'Bar'
}
const {
title,
firstName,
lastName,
...rest
} = record;
//Object spread
const post = {
...options,
type: "new"
}
//array spread
const users = [
...adminUsers,
...normalUsers
]
function greetings({ name = 'Foo' } = {}) { //Defaulting name to Foo
console.log(`Hello ${name}!`);
}
greet() // Hello Foo
greet({ name: 'Bar' }) // Hi Bar
IF is used to execute a block of code based on a condition.
if(condition){
// code
}
Else part is used to execute the block of code when the condition fails.
if(condition){
// code
} else {
// code
}
Switch is used to replace nested If-Else statements.
switch(condition){
case 'value1' :
//code
[break;]
case 'value2' :
//code
[break;]
.......
default :
//code
[break;]
}
For loop is used to iterate a set of statements based on a condition.
for(Initialization; Condition; Increment/decrement){
//code
}
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
while (condition) {
// code
}
Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.
do {
// code
} while (condition);
ES6 introduced classes along with OOPS concepts in JS. Class is similar to a function which you can think like kind of template which will get called when ever you initialize class.
class className {
constructor() { ... } //Mandatory Class method
method1() { ... }
method2() { ... }
...
}
class Mobile {
constructor(model) {
this.name = model;
}
}
mbl = new Mobile("iPhone");