JavaScript
JavaScript allows you to apply logic and programming to your page.
Variables
You know how in your math class you have variables? In programming you have the same thing. Variables can mean anything in programming. From sentences to actual numbers. Examples:
//app.js
var a = 0; //var means variable, and = is for assigning a value. The ';' is optional
var b = 23;
var c = "Maneesh";
var team = "WDC";
Functions
Functions in JavaScript allow you to move functionality to a different part of your code. Each function can do whatever you tell it to. You can have an add function that makes sure that you don't have to type out the same code over and over again. Example:
//app.js
function add(a, b) {
return a + b;
}
Objects
Objects have properties and values. They're kind of an abstract concept. Each object can be different from other objects.
var obj1 = {
prop1: "value1",
prop2: 23
};
var anotherObj = {
prop1: "someObj",
prop2: 300,
unlimited: "properties"
};
Fat Arrow Syntax
These are also known as lambda functions
. Sometimes, when using classes, it's difficult to understand how the this
keyword works because it's different from other languages.
The Fat Arrow Syntax helps with that. The syntax is basically
parameter => thing-to-return
So, for a filter function, we'd originally use
var numbers = [1, 2, 3, 4, 5];
var evens = numbers.filter(function(number) {
return number % 2 === 0;
});
The equivalent syntax would be:
var evens = number.filter(number => number % 2 === 0);
The two are equivalent.
Template strings
You know how it's painful to concat strings together?
ES6 has a fix for that:
var object = {
name: 'Maneesh',
age: 20
};
var es5String = 'Name: ' + object.name + ', age: ' + object.age;
var es6String = `Name: ${object.name}, age: ${object.age}`;
${}
signifies a variable to show
Requesting data from the server
We can request data from a server by using the fetch
function. It allows you to request data from a specific URL. The return type is a promise
. Basically, promises tell you when something is done, and they can be chained with other promises.
For example,
fetch('http://swapi.co/api/people/1').then(res => res.json()).then(data => console.log(data));
The first .then
converts the return variable to be the json
version of the response returned. Then, the promise that chains off will be whatever the result of res.json()
is.
Try it yourself!