🏗️ BaseScript is a programming language, which aims to compile your code to JavaScript.
Why to choose BaseScript?
- It is in the phase of active development, so more and more features are being added constantly. Also, check out RELEASE_NOTES.md, as well as Syntax Highlighter (updated) for the language
- Your ideas are also being reviewed and added, as the language is welcoming collaborations
- It provides you things, that JavaScript lacks:
- Custom operator declaration
- Pipe forward and pipe backward operators
- Emoji variables and operators
- Interfaces
- Typed functions and arguments
- Ability to get compile time errors to prevent runtime errors
- Syntax sugar from other languages, that are so excess
- Ability to customize your code the way you want it, and much more!
- Easy to switch and learn
- Code with ease
- Readable and efficient
- Boilerplate minimization
This page represents the simple to follow documentation of the language.
📬 Email: basescriptnet@gmail.com
📹 YouTube: BaseScript Channel
• Content:
- Getting started
- How to contact the creators
- Variables
- Arrays
- Objects (New Features)
- Strings
- Ternar operator
- Numbers
- BigInts
- Statement block scope
- LOG, print, WRITE and ERROR keywords
- Conditions
- if else statements
- Functions (New Features)
- Custom types
- Debugger
- try|catch|finally statement
- Switch cases
- Loops (New Features)
- Strict mode
- Interfaces
- Operators (New Features)
- Custom Operators
Learn more about CLI usage.
Install via npm
npm i basescript.js -gAt any directory use
bsc -f <file_name> [options?]For help use
bsc -helpTo install globally after git clone, you can use
npm install -g ./[Deprecated]: Include built-in functionality in .bs files
If you already have it in the main file, connected files won't need it (as well as with -r flag)
#include<builtins>Run from CLI without an output file
bsc -f <file_name> -rVariable declaration
letidentifier=valueletnum,num1=1,num2
\num3// equivalent to let num3Const declaration
constidentifier=valueVariable or value reassignment
identifier=valuearray[0]=valueVariable or value reassignment
identifier=valueObject.doSomething=valueArray creation
newArray(length)// length is optional[0,1,2]Getting an item from an array
array[index]Getting a slice of an array
// @params start:end[:direction(1 or -1)]// direction is optionalarray[start:end:direction]Getting the last element of the array
array[]Reassigning to the last element of the array
array[]=valueObject creation
newObject()// not recomended{x: 1}Accessing items of the object
object.xobject['x']Assigning multiple items at once using
.{}operator
letobject={a: 'a'}object.{b: 'b',c: 'c'}// object is {a: 'a', b: 'b', c: 'c'}String creation
newString()// not recomended"Hello world"'Programming is awesome'`I am amultiline string!`String item retraction
"Hello world"[4]// outputs 'o'String last item retraction
"Hello world"[]// outputs 'd'String slice
// @params start:end[:direction(1 or -1)]"Hello world"[0:5:-1]// outputs 'olleH'The typeof operator returns a string
// returns the type of the valuetypeofvaluetypeof(value)Regular JS way
isNaN(value) ? 1 : 0isNaN(value) ? isFinite(value) ? 1 : 0 : -1Shortened way
With if else
trueifisNaN(value)elsefalseDeclaration
// All followings are examples// of the same Integer 100010001000.001_0001_000.00The sizeof operator returns a number
// this returns the length of the object keys// or if not iterable - 0sizeofvaluesizeof(value)BigInts are threated as numbers, but return typeof BigInt
1000n1_000n// 1000.00n will throw an error// floating point numbers are not allowedExample with if block
ifvalue{
...statements}ifvalueBEGIN...statementsENDifvaluedostatementif value:
statementprint and LOG
// they do the same thing// just a syntax sugarprint10// console.log(10)print(10)// console.log(10)printifdefinedI_dont_exist// will not print anything unless the condition is truthy!LOG"hello world"// console.log("hello world")// appends the message to the HTML body element// equivalent to document.write() methodWRITE"Message"// document.write("Message")```-->> ERROR```javascript// equivalent to console.error() methodERROR"Something went wrong"// console.error("Something went wrong")ERRORiferrorMessage// shows an error if errorMessage is not falsyComparision operators
==,!=,===,!==,>,<,>=,<=,is,isnot// is transforms into ===// is not transforms into !==Multivalue comparision
// Note: list of values always must be righthandname==('John','Danny','Charlie')// automatically transforms intoname=='John'||name=='Danny'||name=='Charlie'random>(some_number,other_number,20)// same asrandom>some_number&&random>other_number&&random>20// basically said, you have a callback result for your expression// whatever the first two arguments are,// it needs to be at least more, than 20
↔️ Ternary if
numifnum>0numifnum>0andnum<5elsenum==undefinednum ? num>0num ? num>0andnum<5 : num==undefinedIf statement without else
ifnum<0:
num=0ifnum<0{num=0num1=10}if(num<0):
num=0if(num<0){num=0}If statement with else
iftemperature>25:
print"It's hot!"elseprint"It's cold!"Unless statement
unless isAdmin:
print"You don't have access."// same asif(!isAdmin){console.log("You don't have access.");}Declaration
functiona(){// ...statementsreturnvalue}// if no arguments are carried,// no parenthesis are requiredfunctiona{// ...statementsreturnvalue}// same asdefa(){// ...statementsreturnvalue}// ordefa{// ...statementsreturnvalue}Shortcut for return
returnvalue// same as=>valuefunctionadd(a,b):=>a+bCalling functions
add(10,20)If a function needs to be called multiple times, use the
->()operator
letelementsToWatch=document.querySelector->('#login','#password','#submitBtn',)// returns an array of elementsletcontent=readFile->(&('header','utf8'),&('content','utf8'),&('footer','utf8'),).join('\n')// returns an array, then uses the join methodFor object properties, use
->[]operator to return an array with multiple property calls
letgame=newGame()game->[player,getEnemies(),getEntities()]// returns an array of the property call results// Note: all of those are methods and properties of game// but you won't need to specify `game.player`. Simple:)// This, in fact, uses the javascript `with` statement under the hood for now, which might be updated for safety purposes in the futureTyped arguments and args constant
// this ensures that a and b are integers// anything else will throw an errorfunctionadd(Inta,Intb){returna+b}// only strings are allowedfunctionsay(Stringtext){WRITEtext// deprecated}Declaration
typeNotEmptyArray(Arrayvalue){ifvalue.length!==0: =>true}Notes: type name must start with uppercase letter
Exactly one argument is required
Starting the debugger
ifnum<0{
debugger
}try without catch and finally
try: isWorking(1)// same as:try{isWorking(1)}// catch block is automatically inserted// automatically outputs console.warn(err.message)try with catch
try: isWorking(1)
catch: console.error(err)// variable err is automatically declared// same as:try{isWorking(1)}catcherr{console.error(err)}try with finally
try: isWorking(1)
finally: doSomethingElse()// same as:try{isWorking(1)}finally{doSomethingElse()}Declaration, cases?, default?
switchtypeofvalue{case'String':
returnvaluecase'Number':
case'Null':
case'Undefined':
case'NaN':
returnvalue+'';
default: return'';}To instantly break the case, use
case*feature
leterror=''switcherrorNumber{case*403: error='Forbidden'case*404: error='Not Found'case*500: error='Internal Server Error'}Use
switch*clause as a value
leterror=switcherrorNumber{case403: 'Forbidden'case404: 'Not Found'case500: 'Internal Server Error'}Declaration using
timeskeyword (not a reserved one)
8times{print'Yes!'}// Note: For now, only a numeric value is allowed before `times` keywordDeclaration of while loop
whileisTrue{printtrue}// orwhile(isTrue):
printtrueDeclaration of for loop
forkeyinobject{printobject[key]}forvalueofobject{printvalue}foriofrange(0,10){printi}forifrom0till10{printi}forifrom0through10{printi}// notice, const or let are alowed here, but not necessaryfori=0;i<10;i++{printi}Declaration
'use strict'// learn more at https://www.w3schools.com/js/js_strict.aspDeclaration
interfacePerson{name: String,age: Int,children: Person[]|Null}Usage
letpeople=[]functionaddToArray(Personperson){people.push(person)}addToArray({name: 'John',age: 19,children: null})Arrow and dot operators,
->[],->(),.{}(see Functions, Objects)
->()// Calls a function if used on functions multiple times, depending on argument length->[]// Calls an object property/properties multiple times, without the need to refer to the object each time.{}// assigns or reassigns multiple properties and methods to an object at once, and returns the resultArithmetic Operators
+Plus-Minus*Multiply/Divide~/Divideanddropthefloatingpart%Modulus**Exponentiation++Increment--DecrementLogical Operators
&&Logicaland||Logicalor!LogicalnotBitwise operators
&AND|OR~NOT^XOR<<Leftshift>>Rightshift>>>UnsignedrightshiftType And Size Operators
typeof// describes the type of the objectsizeof// describes the size of the object, or returns nullThe instanceof operator
valueinstanceofArray// as well asvaluenotinstanceofArray// orvalue!instanceofArrayThe in operator
valueinobject// as well asvaluenotinobject// orvalue!inobjectPipe Forward And Pipe Back Operators
|>Pipeforward<|Pipeback// example// pipe forwardnum+5|>Array// Same as Array(num + 5)num+5|>Array(0,1)// Same as Array(num + 5, 0, 1)num+5|>Array(0,1,.)// Same as Array(0, 1, num + 5)' How\'s it going? '|>escape|>trim|>write('file.txt',.)// pipe backwrite('file.txt',.)<|trim<|escape<|' How\'s it going? 'Declaration
// operator "#" [A-Za-z0-9_\/*+-.&|$@!^#~]:+ ...operator #/(Numberleft,Numberright){ifisNaN(left/right): return0returnleft/right;}Usage
// outputs 0 instead of NaNprintInfinity #/InfinityThe documentation is not final, and more examples and syntax sugar tricks will be added
We are constantly updating, fixing and adding new features!
😉 Free Software, Hell Yeah!
This project is open-sourced software licensed under the MIT License.
See the LICENSE file for more information.