Intro to programming - CheatSheet

node v14.20.1
version: 2.0.0
endpointsharetweet
Topic 0 - Expressions 1. Javascript is an interpreted language. 2. The interpreter reads code from top to bottom. 3. It interprets expressions, in this case Javascript expressions. So an expression is the minimal unit of computable code which produces a value. NOTE: While reading this notebook keep in mind that RunKit will automatically try to print out the result of evaluating the latest expression on each block of code. Examples:
"this is a string expression"; 'this is another string expression, and below me is a number expression'; 42; const aVariableDeclaration = 'is an expression'; // By the way, comments like this one are NOT expressions /** Or like this multi line comment which is also not an expression Please remember that: it is good practice to finish most expressions with a semicolon **/ // more expression examples below: 3 * 5; true; function functionDeclarationsAreExpressionsToo() {}; 5 > 10; ['one', true, 3].map(value => typeof value); "something" === "nothing"; // RunKit will print out the result of evaluating this last expression
Topic 1 - Primitives in Javascript In Javascript there are six primitive types: - String : This one is for text strings - Number : You guessed right, this is for numbers - Boolean : Can be either True or False - undefined : Name is kinda self explainatory but it has some catches (until you start dealing with some exotic stuff, you will come across these two below only once or twice) - BigInt : For big numbers - Symbol : For unique inmutable identifiers
/** Strings **/ "this is a string expression using double quotes, gotta escape the \"double quotes\" but not the 'single quotes' "; 'this is a string expression using single quotes, gotta escape the \'single quotes\' but not the "double quotes" '; `this is a string template expression using backticks no need to escape "double" or 'single' quotes `; "you can " + 'concatenate strings ' + `with the addition '+' operator`
/** String templates **/ const aStringVariable = 'strings from variables'; `string templates like this one can interpolate ${aStringVariable + ' or expressions'}, see?` // note the backticks
/** Numbers **/ 42; Number("42"); parseInt('42'); 12 + Number('12') + parseInt("18"); // Not really much to it, you just express the number or convert from a string; // Keep in mind that the order of operators can be influenced by the use of parentheses (3 + 5) * 10 // resolves to 80 3 + (5 * 10) // resolves to 53
/** Booleans **/ true; false; true === false;
// You will usually get a boolean as a result of evaluating an expression 3 > 5; // false 123 < 321; // true 'hello' === 'bye bye'; // false 'this string has length of 39 characters'.length === 39; // true
Bonus Topic - Variable Assignment You can assign the result of evaluating an expression to a space in memroy called a variable. This can be seen as giving 'nicknames' to expressions but is better to think of it as storing something on a locker or a bank box and getting a ticket to gain access to this locker to retrieve the result of the expression you stored there. Consider the example below:
// First we store an expression on a locker and get a ticket const ticketToSomeLocker = "This is an" + " expression which" + " evaluates to a string"; // Now we can use the ticket to retrieve the contents // runkit will evaluate the line below and print out our string ticketToSomeLocker
In Javascript there are three flavours of variables: const, let and var - const: We use this to store things we don't mean to modify or constants. You will use this 99.9% of the time. - let: In contrast to 'const', we use this to store things that we mean to change later. WARNING: 'let' should be avoided when programming in the style we are learning here. - var: is like a jack-of-all trades but is really better to JUST NEVER USE IT and stick to 'const' and 'let'. If you want to know why read this: https://softwareengineering.stackexchange.com/questions/274342/is-there-any-reason-to-use-the-var-keyword-in-es6/323282 Some examples below:
// storing some strings const someString = "i am a string"; const composedString = someString + " too"; // Store numbers const baseOfTriangle = 25; const thisIsAFloatingPointNumber = 5.4321; // Store booleans const isOpen = false; const fiveIsHigher = 5 > 3; // true // Changing a let variable let x = 'yolo'; x = 'yoli'; x; // outputs yoli
Topic 2 - Functions Functions are expressions which allow to define parametrizable blocks of code. This can be read as: provided 0 or more parameters the function will execute a block of code when called. In JS, a function is commonly created in either of two ways: - by a function expression - by a function declaration
Function Expressions
// A function is "expressed" to the interpreter by first defining the parameters it expects // The function's body comes next separated either by // an arrow '=>', by a code block in curly braces '{ ... }', or both. // This is the simplest syntax for an arrow function expression without parameters. () => 'I have no params and will always return this string'; // This is the syntax for an arrow function expression with a body. (parameter, otherParameter) => { return 'this is the return value, again we will return a string just as an example' }; // This is the syntax for a normal or 'classic' anonymous function expression (function(duckies, doggies, otherParameter, evenMoreParameters) { return 'this is the return value, we will return a string here too'; }); // Notice how RunKit evaluates the expression avobe and tells you it is a 'function ()'
// An anonymous function expression can of course be called, when you do this is called an IIFE (function(completeThePhrase) { return `check how we are calling and passing params to this ${completeThePhrase}`; })('immediately invoked function expression or IIFE'); // here we are calling the function and passing the param
// You can make nicer IIFEs with arrow functions ((completeTheSong) => `🎤🎼Never gonna ${completeTheSong}`)('give you up 🎼🎤');
/** Function Declarations **/ // this is the verbose way to declare a function function rickRollOldSkool(completeTheSong) { return `🎤🎼Never gonna ${completeTheSong}`; }; rickRollOldSkool('give you up 🎼🎤');
// You can also declare a function by assigning a function expression to a variable const rickRoll = (completeTheSong) => `🎤🎼Never gonna ${completeTheSong} 🎼🎤`; rickRoll('let you down');
rickRoll('run around and desert you');
Topic 3 - Data structures For the time being we will be focusing our learning on two data structures the array and the dictionary In Javascript the dictionary is also called an object which is very confusing, so we will call dictionaries, dictionaries for now.
/** Arrays **/ // An array is expressed with sqare brackets [] []; // With stuff separated by commas [null, null, null]; // An array is an ordered list of things ['an', 'array', 'of', 'strings']; // It can contain any valid type [ 'one', true, 3, null, function aFunctionInAnArray(){}, 'more stuf ...', String.prototype]; // You access the stuff in an array by its position starting at 0 ['item in position 0', 'item in position 1', 'item in position 2', '...']; // Place it on a variable... const myArray = ['item in position 0', 'item in position 1', 'item in position 2', '...']; // and reference the item you want to retrieve like this: myArray[1];
/** Dictionaries **/ // An array is expressed with curly brackets ... {}; // ...and a list of keys and values divided by a semicolon { someKey: 'some value', anotherKey: 'some other value' } // With stuff separated by commas [null, null, null]; // An array is an ordered list of things ['an', 'array', 'of', 'strings']; // It can contain any valid type [ 'one', true, 3, null, function aFunctionInAnArray(){}, 'more stuf ...', String.prototype]; // You access the stuff in an array by its position starting at 0 ['item in position 0', 'item in position 1', 'item in position 2', '...']; // Place it on a variable... const myArray = ['item in position 0', 'item in position 1', 'item in position 2', '...']; // and reference the item you want to retrieve like this: myArray[1];
Arrays like other types in JS have useful "superpowers" we often and boringly refer to as Methods. For now we will focus on three superpowers of the Array class: - map() - filter() - reduce() All these will help us by going to each item on an array and perform some action on it ... that is they will take a function and for every item in the array these methods will call the function and pass the value of the item to this function as a parameter. Come back to read this paragraph avobe after going through the examples
/** map() **/ // The map method takes a function and applies the function to each item one at a time, and it expects the function // to return a new value (it can be the same) so that it can fill a new array with all the new values // Let's declare a function that will take some string as a parameter and will prepend it with "Crazy". const addCrazy = (someString) => `Crazy ${someString}`; // we can test this function by passing some string to it addCrazy('bunny');
// now we declare an array with random words const randomWordsArray = ['pants', 'eyes', 'stuff', 'times']; // And we use the map() method on the randomWordsArray to get a new "Crazy" array const randomCrazy = randomWordsArray.map(addCrazy);
/** filter() **/ // The filter method takes a 'Test' function and applies it to each item on the array one at a time, it expects the function to return a boolean value and returns a new array containing only those items which evaluated to a truthy value. // A function to test for letter e on a string, returns true if found const testForLetterE = (item) => item.search(/e/) > -1; // We apply the filter to our crazy array defined before randomCrazy.filter(testForLetterE);
/** reduce() **/ // The reduce method will take a reducer function and an initial value. The reducer function will take two mandatory parameters (and two optional params) the first one being the accumulator and the second the current value. // It can be used to get a result from an operation requiring ALL of the items in an array rather than the individual values (which is the focus of other methods like `map()` and `filter()`) const reducerFunction = (accumulator, currentValue) => accumulator + 'Crazy ' + currentValue + ', '; randomWordsArray.reduce(reducerFunction, 'All this stuff is crazy: \n');
Loading…

no comments

    sign in to comment