JavaScript Basics
Variables
Use a variable when you need to store something for later 📦. Name them to help you know what is stored in them, but don’t use spaces in the name. You can change a variable’s value later if you need to.
Create a new variable with the var
keyword:
var someFantasticVariable = “a great var”;
Use the variable name (after you create it) to substitute its value:
console.log(someFantasticVariable);
Overwrite the value of the variable using the =
operator:
someFantasticVariable = 15;
Strings
Strings are words, single characters, sentences, or text of any kind 🕮. Use quotes to show you want a string:
var myString = “JavaScript is all right!”;
Numbers
Use numbers when you need to represent a quantity 💯. Whole numbers and decimal fractions are created the same way in JavaScript:
var myOne = 1;
var myFivePointOne = 5.1;
Booleans
Booleans are ways to represent things that are true 🗹 or false 🗵!
var myFantasticTrueness = true;
var myFantasticFalseness = false;
Comments
Use comments to make a line not run ⛔:
// console.log(“I won’t run ”);
console.log(“Staying Busy!”); // runs fine.
or leave notes on the code for later.
// I am a comment! Humans love me 😘.
Arrays
Arrays are lists of other values 📋. Arrays in JavaScript can have different types of values. Use square brackets around values to show you need an array, and separate values with commas:
var myGreatArray = [ 15, 16 ];
Get values back from them using square brackets and indexes starting at 0:
console.log(myGreatArray[0]; // prints “15”
myGreatArray[1] = 17; // changes 16 to 17
Dictionaries
Dictionaries are strong 💪 variables! They let you store other values in named slots. Almost everything in JavaScript is a dictionary (including the code you write 🤯). Sometimes they are called objects. Use curly braces to show you need a dictionary…
var myDictionary = {
thisIsANumber: 15,
thisIsAString: “Wow another string”
};
…and use a period followed by the name to reference nested dictionary values later. You can also use strings to access values. These lines do the same thing:
myDictionary.thisIsANumber = 16;
myDictionary["thisIsANumber"] = 16;
the next two lines both print 16:
console.log(myDictionary.thisIsANumber);
console.log(myDictionary[“thisIsANumber”]);
Operators
Calculate stuff with operators. There are tons of these guys, so only some are here – sorry not sorry.😊
Operator | Example | Explanation |
---|---|---|
Assignment | a = b | Load (put) b into a |
Addition | a + b | Add a to b |
Division | a / b | Divide a by b |
Subtraction | a – b | Subtract b from a |
Multiplication | a * b | Multiply a times b |
Remainder | a % b | The remainder of a divided by b |
Exponent | a ** b | Raise a to the b th power |
And | a && b | Are both a and b true? |
Or | a || b | Is a or b true? (both might be true) |
Not | !a | true if a is falsefalse if a is true |
Equality | a == b | Do a and b have kinda equal values? |
Strict Equality | a === b | Do a and b have the same type and value? |
Greater than | a > b | Is a larger than b? |
Greater than or equal | a >= b | Is a larger or equal to b? |
Less than | a < b | Is a smaller than b? |
Less than or equal | a <= b | Is a smaller or equal to b? |
Nullity | a?? | Does a even have a value? |
Ternary | a ? b: c | If a, then b, else c. Pretty iffy |
Increment | a++ | Make a one greater: changes a! |
Decrement | a-- | Make a one less: changes a! |
Parentheses
Use parentheses to clarify ☀ the order of your expressions. If it gets too hard to understand 😕, give yourself a break and put it into a variable instead:
var a = true;
var b = false;
var c = 10;
// d is true
var d = (a && (!b)) && ((c * 4) == 40);
Style
Indent your code, put statements on their own lines, and use line breaks so you don’t have to scroll horizontally:
// Hard to read, but I guess it works
function someFunc(){a=15;console.log(a);}
…but this is so much better 👒👔👠!
function someFunc(){
a=15;
console.log(a);
}
Flow Control
Normally, JavaScript just runs code in order which is BORING! 😴
console.log(“I run first!”);
console.log(“I run second!”);
console.log(“I run… Oh, you get it. ”);
For-Loops
A for-loop does something so long as its test is true. For loops love 😍 lists, but their syntax is… unique 🤪…
// prints: “a \n great \n list \n”
var aList = [“a”, “great”, “list”];
for(var i = 0; i < aList.length; i ++){
console.log(aList[i]);
}
While-Loops and Do-Loops
…but there are ways to loop ⮔ without a list, too:
var someTestableValue = true;
// runs only if someTestableValue is true
while (someTestableValue){
someTestableValue = doSomethingElse();
}
// always runs once and then checks if true
do {
someTestableValue = doSomethingElse();
} while (someTestableValue)
Branches
You can use branching 🌲 to run code if something conditionally. The simplest is an if
-block, but you can add else
and else if
s after you want:
if(someVar == 10) {
console.log(“someVar is ten”);
}
else if(someVar < 0){
console.log(“someVar is negative.”);
}
else if(someVar >= 1000){
console.log(“someVar is pretty big!”);
}
else {
console.log(“someVar is ” + someVar);
}
Functions
Functions let you reuse ♲ code you’ve already written. When we use the
function, we say we call or invoke it. Give something
back to the caller with return
:
function someUsefulCode(funcArg){
var aNewVar = “Who am I!? ” + funcArg;
return aNewVar;
}
// prints: “Who am I!? I don’t know.”
Var a = console.log(someUsefulCode(“I don’t know.”));
Functions can call ☎ other functions. Functions can even call themselves, a technique called recursion. Just make sure it eventually exits… or your program will eventually crash ⛐:
function countdownFunc(from, to){
console.log(from);
if(from > to){
countdownFunc(from – 1, to);
}
}
this call uses the previous function to print a countdown from 10 to 0:
countdownFunc(10, 0);
When you create a function, JavaScript puts it into a variable which you can call later – you can do a lot of the same things with function names that you can do with variables! But with great power 🕷…
// An empty func!
function aFunction(){}
aFunction = “I am not a function”;
// prints: “I am not a function”
console.log(aFunction);