JavaScript
If you don’t know any JavaScript, this is a quick 5 minute course explaining most things you will need to understand.
Docs
If you need a more in depth explanation you can look up anything on developer.mozilla.org, everything except for the dom will apply to gjs.
Semicolons
Semicolons are optional, as there is automatic semicolon insertions
Logging, printing
// in gjs and other runtimesconsole.log('hello')
// in gjsprint('hello')
Variables
To define a variable use the let
or const
keyword
let someString = 'some-string'let someNumber = 69let someBool = true
const array = ['string', 69, true]
const object = { key: 'value', 'key-word': 'value',}
Flow control
if else
let i = 0if (i < 0) { print('its negative')}else if(i > 0) { print('its more than 0')}else { print('its 0')}
while loop
let i = 0while (i < 5) { print(i) i++;}
for loop
for (let i = 0; i < 5; i++) { print(i)}
for of loop
const array = [0, 1, 2, 3, 4]for (const item of array) { print(item)}
Functions
There are multiple ways to define functions, with the function
keyword or with fat arrow functions, also know as lambda functions in other languages
named function
function fn(param1, param2) { print(param1, param2)}
nameless function assigned to a const variable
const fn = function(param1, param2) { print(param1, param2)}
fat arrow function a.k.a lambda
const fn = (param1, param2) => { print(param1, param2)}
invoke all of them like any other function
fn('hi', 'mom')
default parameter value
function fn(param1, param2 = 'hello') { print(param1, param2)}
fn() // undefined, hello
Destructuring
arrays
const array = [1, 2, 3, 4, 5]const [elem1, elem2, ...rest] = arrayprint(elem1, elem2, rest) // 1, 2, [3, 4, 5]
objects
const object = {one: 1, two: 2, three: 3, four: 4}const {one, two, ...rest} = objectprint(one, two, rest) // 1, 2, {three: 3, four: 4}
useful in function definitions
function fn({ one, two }) { print(one, two)}
fn({ one: 'hello', two: 'mom' }) // hello, momfn() // throws error because undefined can't be destructed
Modules
exporting
export default 'hello'export const string = 'mom'export function fn(...params) { print(...params)}
importing
import hi, { string, fn } from './path-to-file.js'fn(hi, string) // hello, mom
String formatting
use backticks
and ${}
const string = 'mom'const formatted = `hi ${string}`print(formatted) // hi mom