Javascript is case-sensitive
Everything in JavaScript including variables , function names, class names, and operators are case-sensitive. It means that counter and Counter variables are different.
Comments
JavaScript supports both single-line (//) and block(/**/) comments.
// This is a single line comment /* * This is a multiple line * comment block */
Semicolon
Although JavaScript does not require to end a statement with a semicolon (;
), it is recommended to always use the semicolon to end a statement which makes your code more readable.
var number1 = 1; var number2 = 2;
Javascript variables
JavaScript variables are loosely typed which means that variables can hold values with any type of data. Variables are just placeholders for values.
To declare a variable, you use the var or let keyword followed by the variable name.
var pointer = "Welcome!"; point = 100;
Undefined and undeclared variables
An undefined variable is a variable that has been declared. Because we have not assigned it a value, the variable used the undefined as its initial value.
var undefinedMessage; console.log(undefinedMessage); // undefined
An undeclared variable is the variable that has not been declared.
console.log(undeclaredVariable); // ReferenceError: undeclaredVariable is not defined
Global and local variables
In JavaScript, all variables exist within a scope that determines the lifetime of the variables and which part of the code can access them.
Local variables
Variables declared within a JavaScript function, become locally accessible to the function and only that function.
function sayHi(){ //helloMsg is a local variable to the sayHi() function var helloMsg = "Welcome!"; console.log("helloMsg: "+helloMsg); } sayHi(); console.log("helloMsg: "+helloMsg);//Uncaught ReferenceError: helloMsg is not defined
Global variables
A variable declared outside a function, becomes global which all functions on a web page can access it.
/* * Global variables */ var message = "Hello"; function sayHello() { // local variable message = 'Hi'; console.log(message); // which message? } sayHello();// Hi console.log(message); // Hi
If a local variable is not declared, Javascript will create it as a global variable.
But to avoid creating a global variable accidentally inside a function because of omitting the var keyword, you use the strict mode by adding the “use strict”; at the beginning of the JavaScript file (or the function). Note that by using “use strict” modern javascript will be enforced.
<script> "use strict"; window.onload = function() { } </script>
Javascript Data Types
JavaScript has six primitive data types:
JavaScript has dynamic types. This means that the same variable can be used to hold different data types.
var x; // Now x is undefined x = 10; // Now x is a Number x = "Folau"; // Now x is a String
To get the current type of the value of a variable, you use the typeof operator.
let count = 120; // count is a number console.log(typeof(count)); // "number" count = false; // count is now a boolean console.log(typeof(count)); // "boolean" count = "Hi"; // count is now a string console.log(typeof(count)); // "string"
The null type
Javascript defines that null is an empty object pointer. It is a good practice to assign a variable that later holds an object to null so that you can check whether the object is null or not by using the if statement.
let obj = null; console.log(typeof obj); // object if(obj != null) { // call method of the object }
The undefined type
The undefined type is a primitive type that has one value undefined. By default, when a variable is declared but not initialized, it is assigned the value undefined.
The number type
Variables that hold whole number values
var num = 100; var dec = 2.5;
The boolean type
Variables that hold true or false
var isSafe = true;
The NAN type
JavaScript has a special numeric value called NAN, which stands for Not a Number. In fact, it means an invalid number.
console.log('john'/2);//NaN; console.log(NAN/2);//NAN console.log(NAN==NAN);//false
In JavaScript, a string is a sequence of zero or more characters. A literal string begins and ends with either a single quote(‘) or double quote (“). A string that starts with a double quote must end with a double quote and a string that begins with a single quote must end with a single quote.
let greeting = 'Hi'; let s = "It's a valid string"; let str = 'I\'m also a string'; // use \ to escape the single quote (')
The object type
In JavaScript, an object is a collection of properties, where each property is defined as a key-value pair.
let user = { firstName: 'Folau', lastName: 'Kaveinga' };
Null check with ??
The nullish coalescing operator is written as two question marks ??
.
The result of a ?? b
is:
a
is defined, then a
,a
isn’t defined, then b
.let collegeName; console.log("collegeName: "+ (collegeName ?? "no collegeName"));//collegeName: no collegeName collegeName = "BYU"; console.log("collegeName: ", collegeName ?? "no collegeName");// BYU
Cookies
An http cookie AKA web cookie, AKA browser cookie is a small piece of data stored in a text file that a server sends to the user’s web browser. The browser may store it and send it back with later requests to the same server. Typically, it’s used to tell if two requests came from the same browser — keeping a user logged-in.
When a web server sends a web page to a browser, the connection is shut down, and the server forgets everything about the browser. Cookies were invented to solve the problem “how to remember information about the user”:
Cookies are saved in name-value pairs like: username=folauk
When the browser requests another web page from the server, cookies belonging to that page are added to the request. This way the server gets the necessary data to “remember” information about users.
You can use javascript to read cookies this way
document.cookie – gets all the cookies
// function to read a cookie from browser function getCookie(cname) { var name = cname + "="; var ca = document.cookie.split(';'); for(var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; }
LocalStorage
The localStorage object stores the data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, next week, or next year.
// save data to localStorage
localStorage.setItem("key", "value");
//example saving data to localStorage
localStorage.setItem("lastName", "Kaveinga");
// retrieve data to localStorage
var value = localStorage.getItem("key");
// example of retrieving data from localStorage
var lastname = localStorage.getItem("lastName");
// remove data from localStorage
localStorage.removeItem("key");
// example of removing data from localStorage
localStorage.removeItem("lastName");l
// remove all localStorage content for a perticular domain
localStorage.clear();
SessionStorage
The sessionStorage object stores data for only one session. The data is deleted when the browser tab is closed.
// save data to sessionStorage sessionStorage.setItem("key", "value"); //example saving data to sessionStorage sessionStorage.setItem("lastName", "Kaveinga"); // retrieve data from sessionStorage var value = sessionStorage.getItem("key"); // example of retrieving data from sessionStorage var lastname = sessionStorage.getItem("lastName"); // remove data from sessionStorage sessionStorage.removeItem("key"); // example of removing data from sessionStorage sessionStorage.removeItem("lastName");l // remove all sessionStorage content for a perticular domain sessionStorage.clear();
Timing
JavaScript code can be executed in time-intervals either by set a timeout and then execute a funciton or set an interval and then execute a function repeatedly.
setTimeout(function, milliseconds)
// wait 3 seconds and then execute function let timeout = setTimeout(function(){ console.log("timeout!"); }, 3000);
clearTimeout(setTimeout)
/** * clearTimeout * The clearTimeout() method stops the execution of the function specified in setTimeout(). */ // stop timeout from executing. clearTimeout(timeout);
setInterval(function, milliseconds)
/** * setInterval(function, milliseconds) * The setInterval() method repeats a given function at every given time-interval. * */ let interval = setInterval(() => { console.log("fire interval!"); }, 1000);
clearInterval(setInterval)
/** * * clearInterval(interval); */ setTimeout(() => { // stom interval after 6 seconds clearInterval(interval); }, 6000);
The this keyword references the object of which the function is a property. In other words, the this references the object that is currently calling the function.
When this is used alone, the owner is the Global object, so this refers to the Global object. In a browser window the Global object is the Window object.
this in global object
/* * Global this * Alone, this refers to the global object. */ var pageName = "This Keyword"; function showPageName(){ console.log("pageName: " + this.pageName);//This Keyword } showPageName();
this in a method
JavaScript “strict mode” does not allow default binding. So, when this is used in a function, in strict mode, this is undefined.
/** * In a method, this refers to the owner object */ let person = { firstName: "John", lastName : "Doe", id : 5566, fullName : function() {// person is the owner of this function return this.firstName + " " + this.lastName; } }; console.log("fullName: "+person.fullName());//John Doe
this in an arrow function
If this is used in an arrow function, this is referencing outer fields or methods.
/* * this in arrow funciton * Arrow functions are special: they don’t have their “own” this. * If we reference this from such a function, it’s taken from the outer “normal” function. */ let user = { name: "Folau", sayHi() { //If we reference this from such a function, it’s taken from the outer “normal” function. let arrow = () => console.log("arrow name: "+this.name);//arrow name: Folau arrow(); function sayMyName(){ console.log("my name: "+this.name);//my name: } sayMyName(); } }; user.sayHi();
The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action’s eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.
A promise is in one of these states:
A pending promise can either be fulfilled with a value or rejected with a reason (error). When either of these options happens, the associated handlers queued up by a promise’s then method are called. If the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached.
As the then() and catch() methods return promises, they can be chained. The methods promise.then(), promise.catch(), and promise.finally() are used to associate further action with a promise that becomes settled.
<script> let successAction = new Promise((resolve, reject) => { console.log('Initial'); document.getElementById("promisePending").innerHTML = "Starting..."; // do async action here. setTimeout( function() { let apiResponse = {}; apiResponse.id = 1; apiResponse.name = "Folau"; resolve(apiResponse); document.getElementById("promiseFullFilled").innerHTML = "fullfilled"; }, 3000); }); successAction.then((reponse) => { console.log(reponse); console.log('Do this'); }) .catch((error) => { // This is skiped because resolve is called above. console.error('Error'); console.log(error); }).finally(() => { console.log('finally!'); }); let failedAction = new Promise((resolve, reject) => { console.log('Initial'); document.getElementById("promisePending").innerHTML = "Starting..."; // do async action here. setTimeout( function() { let apiResponse = {}; apiResponse.id = 1; apiResponse.name = "Folau"; reject(apiResponse); document.getElementById("promiseRejected").innerHTML = "rejected"; }, 3000); }); failedAction.then((reponse) => { // This is skiped because reject is called above. console.log(reponse); console.log('Do this'); }) .catch((error) => { console.error('Error'); console.log(error); }).finally(() => { console.log('finally!'); }); </script>
Promise with API HTTP requests
<script> const axiosInstance = axios.create({ baseURL: 'http://localhost:8888', timeout: 1000, headers: { "Content-type": "application/json", "token": "foobar" } }); function getUser(){ console.log("getUser"); let headers = { "Content-Type": "application/json", "token":"lovemesomecoding-token" }; let options = {}; options.method = "GET"; options.headers = headers; let id = 1; let url = "http://localhost:8888/users/"+id; let response = axiosInstance(url, options); response.then(response => { let data = response.data; let content = ""; content += "id: "+data.id+"<br>"; content += "firstName: "+data.firstName+"<br>"; content += "lastName: "+data.lastName+"<br>"; content += "email: "+data.email+"<br>"; document.getElementById("getUserContent").innerHTML = content; }).catch(error => { console.log("error"); let errorResponse = error.response.data; console.log(errorResponse); document.getElementById("errorMsg").innerHTML = errorResponse.message; }); } function updateUser(){ console.log("update user"); let headers = { "Content-Type": "application/json", "token":"lovemesomecoding" }; let user = { firstName: 'Folau', lastName: 'Kaveinga', email: 'folaukaveinga@gmail.com', id: 1 }; let options = {}; options.method = "PUT"; options.body = JSON.stringify(user); options.headers = headers; let url = "http://localhost:8888/users"; let response = axiosInstance(url, options); response.then(response => { let data = response.data; let content = ""; content += "id: "+data.id+"<br>"; content += "firstName: "+data.firstName+"<br>"; content += "lastName: "+data.lastName+"<br>"; content += "email: "+data.email+"<br>"; document.getElementById("updateUserContent").innerHTML = content; document.getElementById("errorMsg").innerHTML = ""; }).catch(error => { console.log("error"); let errorResponse = error.response.data; console.log(errorResponse); document.getElementById("errorMsg").innerHTML = errorResponse.message; }); } </script>
Asnyc/await
The async keyword before a function means that function always returns a promise. Other values are wrapped in a resolved promise automatically.
The await keyword makes JavaScript wait until that promise settles and returns its result.
<div class="row"> <div class="col-1"> </div> <div class="col-4"> Get Average Number <br> <button onclick="getAverageNumber()" type="button" class="btn btn-outline-primary">Get It</button> </div> <div class="col-7" id="averageNum"> </div> </div> <script> /* * Async and await */ async function calculateAverage(num1, num2, num3){ // This could be a REST API call let someNumber = await new Promise(resolve => { setTimeout(() => { resolve(3); }, 2000); }); console.log("num1: "+num1 + ", num2: "+ num2 +", num3: "+ num3 + ", someNumber: "+someNumber); return (num1 + num2 + num3 + someNumber) / 4; } function getAverageNumber(){ calculateAverage(2, 3, 4).then(average => { console.log("average"); console.log(average); document.getElementById("averageNum").innerHTML = average; }); } </script>