// Variable declaration and assignmentletx=10;constpi=3.14159;letname="John";// Data typesleti=10;letd=3.14159;lets="Hello";letb=true;leta=[1,2,3];leto={one:1,two:2};
letx=10;// If statementif(x>0){console.log("x is positive");}// If-else statementif(x>0){console.log("x is positive");}else{console.log("x is negative");}// Else-if statementif(x>0){console.log("x is positive");}elseif(x==0){console.log("x is zero");}else{console.log("x is negative");}
Loops
// For loopfor(leti=0;i<10;i++){console.log(i);}// While loopleti=0;while(i<10){console.log(i);i++;}// Do-while loopleti=0;do{console.log(i);i++;}while(i<10);// For-in loopletobj={one:1,two:2,three:3};for(letkeyinobj){console.log(key+": "+obj[key]);}// For-of loopletarr=[1,2,3];for(letelemofarr){console.log(elem);}
Functions
// Function declarationfunctionadd(x,y){returnx+y;}// Function expressionletadd=function(x,y){returnx+y;};// Arrow functionletadd=(x,y)=>{returnx+y;};// Default parametersfunctiongreet(name="John"){console.log("Hello, "+name+"!");}// Rest parametersfunctionsum(...nums){lettotal=0;for(letnumofnums){total+=num;}returntotal;}// Higher-order functionfunctiondouble(x){returnx*2;}functionapply(func,x){returnfunc(x);}letresult=apply(double,10);console.log(result);
Arrays
// Array declaration and initializationleta=[1,2,3,4,5];// Accessing elements of an arrayletfirstElement=a[0];letlastElement=a[a.length-1];// Adding elements to an arraya.push(6);a.unshift(0);// Removing elements from an arraya.pop();a.shift();
Objects
// Object declaration and initializationletperson={name:"John",age:30,gender:"male"};// Accessing properties of an objectletname=person.name;letage=person["age"];// Adding properties to an objectperson.email="john@example.com";// Removing properties from an objectdeleteperson.gender;
Functions
// Function declarationfunctionadd(x,y){returnx+y;}// Function expressionletadd=function(x,y){returnx+y;};// Arrow functionletadd=(x,y)=>x+y;
Classes
// Class declarationclassPerson{constructor(name,age){this.name=name;this.age=age;}getName(){returnthis.name;}getAge()