Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

javascript for dummies

//Define constants (immutable)
const string = "bar"; //Block scope
const int = 1;
const float = 0.2;
const obj = {
    fieldName: "value",
    nestedField: {
        someArray: [
            {
                name: "user1",
                age: 23
            },
            {
                name: "user2",
                age: 48
            }
        ]
    }
};
const array = [1, 2, 3, 4, "foo", "bar", {foo: "bar"}];

//Define variables (mutable) can also be used with all sorts of datatypes
let bar = "baz"; //Block scope

var baz = "lorem"; //Function scope

//Access objects
const firstName = obj.nestedField.someArray[0].name;
const firstAge = obj["nestedField"]["someArray"][0]["name"];

// using destructuring
const { firstName, firstAge} = obj.nestedField.someArray[0];


//Define functions
function myFunc(a, b) {
    return a + b;
}

// Arrow-Functions (ES-6)
const otherFunc = (a, b) => {
    return a + b;
}

//If-Else-Statements
const active = true;

if (active) {
    console.log("Im active, yay!"); // console.log() prints to the console
}else if (active === undefined) {
    console.log("Seems like i dont know...");
}
else {
    console.log("Im not active!");
}

// also possible without curly braces (not recommended):
if (active) console.log("Im active, yay!")
else console.log("Im not active!");

//Ternary Operator (very useful)
console.log(active ? "Im active, yay!": "Im not active!");

//Array prototype methods (some are kinda complicated, so just google them)
const myArr = [1, 2, 3, 4];
let result = 0;

myArr.forEach((myNumber) => { //Loops through every item in the list, while passing each individual number as 'myNumber'
    result += myNumber;
});
//returns 15

//Destructuring objects (ES-6)
const {name, age} = {name: "foo", age: 34};
//console.log(name) -> foo
//console.log(age) -> 34

//Spread Operator (ES-6)
const myArr = [1, 2, 3]
const calculate = (a, b, c) => {
    return a + b + c;
}
calculate([...myArr]) // --> 6

//can also be used to extend arrays or objects!
let myArr = [1, 2]
myArr = [...myArr, 3] // --> [1, 2, 3]

//and more... (but i kinda run out of time for now)
 
PREVIOUS NEXT
Tagged: #javascript #dummies
ADD COMMENT
Topic
Name
1+7 =