What is Javascript?
JavaScript is a scripting or programming language that allows you to implement complex features on web pages.
The programs in this language are called scripts. They can be written right in a web page’s HTML and run automatically as the page loads.
JavaScript can execute not only in the browser but also on the server.
The browser has an embedded engine sometimes called a “JavaScript virtual machine”.
For example:
V8 – in Chrome, Opera and Edge.
SpiderMonkey – in Firefox.
Popular Javascript Frameworks out there you may want to Explore…
- Node.js
- Vue.js
- Ember.js
- Angular.js
- React.js
Topics to cover:
- Variables and Constants
- Arrays and objects
- The Dom
- Functions
- Primitive Types
Variables
A variable is a “named storage” for data.
To create a variable in JavaScript, use the let keyword.
Ex:
let message;
message = 'Hello!';
alert(message); // shows the variable content
More Example programs:
let bucket;
bucket = 'Water';
bucket = 'Soil'; // value changes
alert(bucket);
or…
let admin, name;
name = "John";
admin = name;
alert(admin);
Rules to follow when naming variables:
- The name must contain only letters, digits, or the symbols $ and _.
- The first character must not be a digit.
Ex:
let firstName, lastName, userName etc. // referred to as camelCase
let $ = 1; // declared a variable with the name “$”
let _ = 2; // and now a variable with the name “_”
alert($ + _); // 3
Constants
a constant is an (unchanging) variable to declare we use const instead of let
const pi = 3.14;
pi = 2.44; // trying to reassign, error, can't reassign the constant!
alert(pi);
Uppercase Constants
const BIRTHDAY = ‘18.04.1982’; // make uppercase? yes, why -> We generally use upper case for constants that are
“hard-coded”. Or, in other words, when the value is known prior to execution and directly written into the code.
We can also have something like, const COLOR_WHITE = “#FFFF”;
let color = COLOR_WHITE;
alert(color); // #FFFF its easier to remember white than the hex value #fff
const age = someCode(BIRTHDAY); // make uppercase? (AGE) no, why -> In contrast, age is evaluated in run-time. Today we
have one age, a year after we’ll have another one. It is constant in the sense that it does not change through the code execution. But it is a bit “less of a constant” than birthday: it is calculated, so we should keep the lower case for it.
Arrays
An array is a data structure consisting of a collection of elements In other words Arrays to store ordered collections.
You can create an array with the following syntax:
let arr = [];
let arr = new Array(); // old fashioned rarely used
Ex:
let cars = ["Toyota", "Mercedes", "Tesla"]
alert( cars[0] ); // Toyota
alert( cars[1] ); // Mercedes
We can replace an element:
fruits[2] = 'Filda'; // now ["Toyota", "Mercedes", "Filda"]
…Or add a new one to the array:
fruits[3] = 'BMW'; // now ["Toyota", "Mercedes", "Filda", "BMW"]
The total count of the elements in the array is its length:
let fruits = ["Toyota", "Mercedes", "Filda"]
alert( fruits.length ); // 3
Methods pop/push
- push adds an element to the end.
Ex:
let fruits = ["Toyota", "Mercedes"];
fruits.push("Filda");
alert( cars ); // Toyota, Mercedes, Filda
- pop takes an element from the end.
Ex:
let cars = ["Toyota", "Mercedes", "Filda"]
alert( cars.pop() ); // remove "Filda" and alert it
alert( cars ); // Toyota Mercedes
- shift
Extracts the first element of the array and returns it:
Ex:
let cars = ["Toyota", "Mercedes", "Filda"]
alert( cars.shift() ); // remove Toyota and alert it
alert( cars ); // Mercedes, Filda
- unshift
Add the element to the beginning of the array
Ex:
let cars = ["Mercedes", "Filda"];
fruits.unshift('Toyota');
alert( fruits ); // Toyota, Mercedes, Filda
NB: Methods push/pop run fast, while shift/unshift are slow.
We can also use for loop to iterate over array elements
- For Loop:
Ex:
let arr = ["Toyota", "Mercedes", "Filda"];
for (let i = 0; i < arr.length; i++) {
alert( arr[i] );
}
Objects
objects are used to store keyed collections of various data.
Ex:
We can put properties into {…} as “key: value” pairs:
let user = {
name :"Brian",
surname : "Mweu",
//name : "Merinda"
};
Property has a key (also known as “name” or “identifier”) before the colon “:” and a value to the right of it.
Property values are accessible using the dot notation:
alert(user.name); // Brian
To remove a property, we can use the delete operator:
delete user.name; // undefined Brian has been deleted
The “for…in” loop
The syntax:
for (key in object) {
// executes the body for each key among object properties
}
Ex:
let fruit = {
name: "Mango",
color: "yellow",
price: 10,
};
for (let key in fruit) {
// keys
alert( key ); // name, color, price
// values for the keys
alert( fruit[key] ); // Mango, yellow, 10
}
Functions
Functions are the main “building blocks” of the program.
They allow the code to be called many times without repetition.
Function Declaration
To create a function we can use a function declaration
Ex:
function helloWorld() {
alert( 'Hello world!' );
}
The analogy here is
function name(parameter1, parameter2, … parameterN) {
…body…
}
we call the function using the function name as follows
helloWorld();
We can have local variables inside a function which means they are only local to the function
Ex:
function helloWorld() {
let message = "Hello world my name is Brian"
alert(message);
}
helloWorld();
//alert( message ); // error the variable is a local variable
As we have local variables we also have global variables in a function such as
let price = '20'; // global variable
function showPrice() {
let message = 'The price of a single mango is, ' + price;
alert(message);
}
showPrice();
Functions can have parameters as I described in the syntax above
Ex:
function checkAge(age) {
if(age >= 18) {
return true;
} else {
return confirm('You are under 18!')
}
}
let age = prompt("Enter your age", 18);
if ( checkAge(age) ) {
alert( 'Access granted' );
} else {
alert( 'Access denied' );
}
// Access granted
Functions can return a value back the above example shows it well. Remember we have named the functions within the function declaration I talked about at the start.
Primitives Types
JavaScript allows us to work with primitives (strings, numbers, etc.) as if they were objects.
Let’s look at the key distinctions between primitives and objects.
A primitive Is a value of a primitive type.
There are 7 primitive types: string, number, bigint, boolean, symbol, null and undefined.
An object Is capable of storing multiple values as properties.
Can be created with {}, for instance: {name: “John”, age: 30}. There are other kinds of objects in JavaScript: functions, for example, are objects
Ex:
let brian = {
name: "Brian",
sayHi: function() {
alert("Hi Brian!");
}
};
brian.sayHi(); // Hi Brian!
So here we’ve made an object john with the method sayHi.
A primitive as an object
For instance, there exists a string method str.toUpperCase() that returns a capitalized str.
Here’s how it works:
let str = "Brian";
alert( str.toUpperCase() ); // BRIAN
Simple, right? Here’s what actually happens in str.toUpperCase():
- The string str is a primitive. So in the moment of accessing its property, a special object is created that knows the value of the string, and has useful methods, like toUpperCase().
- That method runs and returns a new string (shown by alert).
- The special object is destroyed, leaving the primitive str alone.
So primitives can provide methods, but they still remain lightweight.
NB:
null/undefined has no methods
The special primitives null and undefined are exceptions. They have no corresponding “wrapper objects” and provide no methods. In a sense, they are “the most primitive”.
An attempt to access a property of such value would give the error:
alert(null.test); // error
Another Ex:
let name= "Brian";
console.log(Object.keys(name));
console.log(Object.values(name));
Output:
(5) ["0", "1", "2", "3", "4"]
(5) ["B", "r", "i", "a", "n"]
So that means we can use methods of Objects on primitives.
The DOM
The Document Object Model (DOM) is the data representation of the objects that comprise the structure and content of a document on the web.
It represents the page so that programs can change the document structure, style, and content.
This is just an introduction on getting started with the Dom
Ex:
For example, document.body is the object representing the tag.
index.html
<body>
<h1 style="text-align:center;">Welcome to Javascript</h1>
<script type="text/javascript" src="script.js"></script>
</body>
Ex:
script.js
document.body.style.background = 'blue'; // make the background red
setTimeout(() => document.body.style.background = '', 4000); // return back
document.getElementById or just id
index.html
<div id="main">
<div id="Main-content">Main Content</div>
</div>
<script>
// get the element
let elem = document.getElementById('main');
// make its background blue
elem.style.background = 'red';
</script>
querySelectorAll
Returns all elements inside elem matching the given CSS selector. Here we look for all elements that are last children:
Ex:
index.html
<ul>
<li>Mango</li>
<li>Oranges</li>
<li>Bananas</li>
</ul>
script.js
<script>
let elements = document.querySelectorAll('ul > li:last-child');
for (let elem of elements) {
alert(elem.innerHTML); // "Bananas"
}
</script>
Modifying the Document
Create a Message
Creating the message div takes 3 steps:
1. Create an element
let div = document.createElement('div');
2. Set its class to “alert”
div.className = "alert";
3. Fill it with the content
div.innerHTML = "You've 4 unread Mail Notifications.";
Ex:
index.html
<style>
.alert {
padding: 15px;
border: 1px solid #d6e9c6;
border-radius: 4px;
color: #3c763d;
background-color: #dff0d8;
}
</style>
script.js
let div = document.createElement('div');
div.className = "alert";
div.innerHTML = "You've 4 unread Mail Notifications.";
document.body.append(div);
setTimeout(() => div.remove(), 1000); // you can remove the node and set the timeout
We will dig deeper into the Dom in the coming Javascript tutorials.