Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //variable
- //VALID
- var man;
- var blackDog; // This is the best way to name variables with several words
- // INVALID
- var 1girl;
- var -girl;
- //let shares a lot of similarities with var but unlike var has scope constraints.
- let x, y, z;
- let x = 50, y = 20, z = 3;
- //Unlike var, variables cannot be re-declared using let, trying to do that will throw a Syntax error: Identifier has already been declared.
- let x = 20;
- let x = 50;
- console.log(x); // SyntaxError: identifier "x" has already been declared.
- //Use const when you are sure a variable will not be redeclared.
- //A variable declared with **const** MUST be initialized.
- const x; // SyntaxError: missing initializer
- //You are not allowed to change the value of a variable declared with const.
- //However, if you declare an object as const, you are able to change the properties.
- // String
- const name = "Sarai"; // This is a string using double quotes
- const name2 = 'Sarai'; // This is also a string using single quotes
- const name3 = `Sarai`; // This is another string using computed string `` it accepts mutation using ${whatever}
- // Number
- const number = 0; // Simple
- // Boolean
- const boolean = false; // Can only be true or false
- // Object
- const object = {
- key: value,
- }; // This is an object that has a key and a value
- // Array or List
- const array = []; // This is an empty list
- const array2 = ['Sarai'] // This is a list with a string
- const array3 = [0]; // This is a list with a number
- const array4 = [true] // This is a list with a boolean
- const array5 = [{key: 'Sarai'}] // This is a list with a object with a key called key and value of a string
- // Null
- const nullVar = null;
- // Undefined
- const undef; // This is an undefined variable
- const undef2 = undefined; // This is an undefined variable (explicit)
- //functions
- function validFunctionName(parameter) {
- return statement;
- }
- bark();
- //A function can have multiple parameters or no parameters at all
- //Function Expression defines a named or anonymous function
- var fullName = function(firstName, lastName) {
- return `${firstName} ${lastName}`;
- }
- fullName("Jamal", "Uddin"); // Jamal Uddin
- //Arrow Function: An Arrow Function Expression is a shorter syntax for writing function expressions. Arrow functions do not create their own this value.
- const double = (value) => {
- return value * 2
- }
- double(10); // 20
- const double2 = value => value * 2;
- double2(10); // 20
- const noise = () => console.log("Pling");
- noise(); // Pling
- const noise2 = _ => console.log("Pling");
- noise2(); // Pling
- const multiply = (a = 2, b = 3, c = 1) => a * b * c;
- multiply(2, 2, 2); // 8
- multiply(2, 2); // 4
- multiply(3); // 9
- multiply(); // 6
- // the return keyword can ONLY be used inside of a function.
- function returnOnlyOnce(){
- return "Hello";
- return "Goodbye";
- }
- returnOnlyOnce(); // "Hello"
- //Shorthand method definition can be used in a method declaration on object literals and ES6 classes. We can define them using a function name, followed by a list of parameters in a pair of parenthesis (para1, ..., paramN) and a pair of curly braces { ... } that delimits the body statements.
- const fruits = {
- items: [],
- add(...items) {
- this.items.push(...items);
- },
- get(index) {
- return this.items[index];
- }
- };
- fruits.add('mango', 'banana', 'guava');
- fruits.get(1); // banana
- //A generator is a function that can stop midway and then continue from where it stopped. In short, a generator appears to be a function but it behaves like an iterator.
- function * generatorFunction() {
- yield 'Hello, ';
- console.log('I will be printed after the pause');
- yield 'World!';
- }
- const generatorObject = generatorFunction();
- console.log(generatorObject.next().value);
- console.log(generatorObject.next().value);
- console.log(generatorObject.next().value);
- // output should be following below.
- // Hello,
- // I will be printed after the pause
- // World!
- // undefined
- //The Function constructor creates a new Function object.
- var sum = new Function('a', 'b', 'return a + b');
- console.log(sum(2, 6)); // 8
- //conditionals
- if (condition a) {
- // code that will execute if condition a is true
- } else if (condition b) {
- // code that will execute if condition b is true
- } else if (condition c) {
- // code that will execute if condition c is true
- } else {
- // code that will execute if all above conditions are false
- }
- //The ternary operator, also known as the conditional operator, is used as shorthand for an if...else statement.
- //A ternary operator is written with the syntax of a question mark (?) followed by a colon (:), as demonstrated below.
- //// Set age of user
- let age = 20;
- // Place result of ternary operation in a variable
- const oldEnough = (age >= 21) ? "You may enter." : "You may not enter.";
- // Print output
- oldEnough;
- //loop
- while (n < 3) {
- n++;
- }
- //classes have properties and methods
- class Car {
- constructor(brand) {
- this.carname = brand;
- }
- present() {
- return "I have a " + this.carname;
- }
- }
- mycar = new Car("Ford");
- document.getElementById("demo").innerHTML = mycar.present();
- //The constructor method is special, it is where you initialize properties, it is called automatically when a class is initiated, and it has to have the exact name "constructor"
- class Car {
- constructor(brand) {
- this.carname = brand;
- }
- present() {
- return "I have a " + this.carname;
- }
- }
- mycar = new Car("Ford");
- document.getElementById("demo").innerHTML = mycar.present();
- object.name = "Blah"
- //^this is a setter
- object.name
- //without the equal is a getter
- const myObj = { a: 1, b: 2, c: 3};
- console.log(a); // undefined
- const { a } = myObj;
- const a = myObj.a;
- console.log(a); // 1
- //Access Object Properties in JavaScript
- //Dot property accessor -> expression.identifier
- const hero = {
- name: 'Batman'
- };
- // Dot property accessor
- hero.name; // => 'Batman'
- //Square brackets property accessor
- expression[expression]
- const property = 'name';
- const hero = {
- name: 'Batman'
- };
- // Square brackets property accessor:
- hero['name']; // => 'Batman'
- hero[property]; // => 'Batman'
- //Object destructuring
- const { identifier } = expression;
- const hero = {
- name: 'Batman'
- };
- // Object destructuring:
- const { name } = hero;
- name; // => 'Batman'
- //The AND (&&) and OR (||) logical operators both require two operands, and are used to perform Boolean operations on their operands.
- //&& operation returns true only when both operands are true, otherwise it returns false.
- //|| operation returns false only when both operands are false, otherwise it returns true.
- false && true || true; // true
- false && (true || true); // false
- // number literal
- 0xFF
- // array literal
- []
- // object literal
- {}
- // regexp literal
- /^\d+$/
- // logical AND operation
- (x && y)
- // bitwise XOR operation
- (x ^ y)
- // ternary operation
- (x ? y : z)
- // arithmetic operation
- (x + y) / z
- // assignment
- x = 'string'
- // function expression
- (function x(y) {})
- // function invocation
- x(100)
- // object property access
- obj.students[0].name
- //If you want to access any element in an HTML page, you always start with accessing the document object.
- document.getElementById(id) //Find an element by element id
- document.getElementsByTagName(name) //Find elements by tag name
- document.getElementsByClassName(name) //Find elements by class name
- //Changing HTML Elements
- element.innerHTML = new html content //Change the inner HTML of an element
- element.attribute = new value //Change the attribute value of an HTML element
- element.style.property = new style //Change the style of an HTML element
- element.setAttribute(attribute, value) //Change the attribute value of an HTML element
- //Adding and Deleting Elements
- document.createElement(element) //Create an HTML element
- document.removeChild(element) //Remove an HTML element
- document.appendChild(element) //Add an HTML element
- document.replaceChild(new, old) //Replace an HTML element
- document.write(text) //Write into the HTML output stream
- //The getElementsByClassName method of Document interface returns an array-like object of all child elements which have all of the given class nam
- var elements = document.getElementsByClassName(names); // or:
- var elements = rootElement.getElementsByClassName(names);
- //HTML EVENT HANDLERS
- onblur onclick onerror onfocus
- onkeydown onkeypress onkeyup onmouseover
- onload onmouseup onmousedown onsubmit
- //Add an event listener that fires when a user clicks a button:
- document.getElementById("myBtn").addEventListener("click", displayDate);
- element.addEventListener(event, function, useCapture);
- //callback promises and async
- // v set timeout takes in a call back function adn it takes in a certain amount of time that you want to delay whatever you put in there, in this case 1second
- function getPosts () {
- setTimeout(function(); {
- }, 1000)
- }
- //you can also do it as an arrow function
- function getPosts () {
- setTimeout (() => {
- }, 1000)
- }
- git init
- - initialises folder as git repository
- git log -oneline
- - see a brief log of commits
- git add .
- - adds files to the staging area
- git checkout [comit log number] [file name]
- e.g. git checkout 900cfcf index.html
- - will checkout that file into my current working directory
- - this has already been staged (need_help - understand staged?) , so this git checkout will pull out an older version of the file and then will replace what is on the current directory and also check it into the staging area
- - if I do that and realise that this is what I want then I can just do annother commit
- git reset HEAD index.html
- - but if I dont like the above and want to revert I do ^
- - the modified version I had checkedout is still there but has been unstaged
- git checkout -- index.html
- - here my file has been restored to what it was before I reverted stuff (need_help - why double minus sometimes?)
- npm init
- - initialises a package.json file for your project
- npm install lite-server --save-dev (need_help)
- - "--save-dev" specifies that this lite-server is used for development dependency for our project
- - in installing a module on which project is directly dependent on then I would use "--save"-option"
- (need_help) I had to add lite-servermanually in lines 7 and 9 of my json package. I have no idea why I did dis, I understand that dis means going forward dis will start the lite server but I don't understand why? npm start would start a server already before
- theory - a live-server equivalent already installed as a global dependancy? that is why "npm start" already does something but because in dis case it is just a git repository that I made I had to do it manually. when I create a react project this package? node module? is already installed
- .gitignore
- -You normally dont want to upload the node modules folder as dis can be recreated by typing "npm install", to avoid certain folders getting commited you need to create a gitignore file
- create-react-app --help
- -Brings out a set of instructions on how to use the create react appears
Add Comment
Please, Sign In to add comment