What is Javascript
JavaScript is a lightweight programming language that web developers commonly use to create more dynamic interactions when developing web pages, applications, servers, and or even games. Developers generally use JavaScript alongside HTML and CSS The scripting language works well with CSS in formatting HTML elements. However, JavaScript still maintains user interaction, something that CSS cannot do by itself. JavaScript’s implementations within the web, mobile application, and game development make the scripting language worth learning.
So in this tutorial we would be very practical in our approach to learning. lets dive.
First step is to create a folder for your project, open it with your IDE (VS Code, Notepad ++, Sublime etc.).
So we will be creating two files index.html and app. js
, then we would add the basic code and also link the script like so
//Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Javascript sandbox</title>
</head>
<body>
<h1>Javascript sandbox section 2</h1>
<script src="app.js"></script>
</body>
</html>
Working with console in our app.js
A Web console is a tool which is mainly used to log information associated with a web page like: network requests, JavaScript, security errors, warnings, CSS etc. It enables us to interact with a web page by executing JavaScript expression in the contents of the page. In JavaScript, the console is an object which provides access to the browser debugging console. We can open a console in web browser by using: Ctrl + Shift + I for windows and Command + Option + K for Mac. The console object provides us with several different methods like:
log()
error()
warn()
clear()
time() and timeEnd()
table()
count()
group() and groupEnd()
custom console logs
Modern browsers have development tools built in to work with JavaScript and other web technologies. These tools include the Console which is similar to a shell interface, along with tools to inspect the DOM, debug, and analyze network activity. The Console can be used to log information as part of the JavaScript development process, as well as allow you to interact with a web page by carrying out JavaScript expressions within the page’s context. Essentially, the Console provides you with the ability to write, manage, and monitor JavaScript on demand.
Practical examples
// log in console
console.log('Hello world'); //string
console.log(123); // number
console.log(true); // boolen
var greetings = 'Hello Jacob'
console.log(greetings);
console.log(['joy','john','temi']) //array
console.log({a:1,b:2,c:3,d:4}) //objects
console.table({a:1,b:2,c:3,d:4}) //print object as a table
console.error('this is an error');
console.warn('this is a warning');
console.time('hello');
for($i=0;$i<=9;$i++){
console.log('hello', $i)
}
console.timeEnd('hello');
Defining Variables in Javascript
Variable means anything that can vary. In JavaScript, a variable stores data that can be changed later on.
In JavaScript, a variable can be declared using var
, let
, const
keywords.
- var keyword is used to declare variables since JavaScript was created. It is confusing and error-prone when using variables declared using
var
. - let keyword removes the confusion and error of
var
. It is the new and recommended way of declaring variables in JavaScript. - const keyword is used to declare a constant variable that cannot be changed once assigned a value.
Here, we will use the var keyword to declare variables. To declare a variable, write the keyword var followed by the name of the variable you want to give, as shown below.
// var, let, const
var color = 'red';
console.log(color);
// reasign variable
color = 'yellow';
console.log(color)
// initialize variable
var greetings;
greetings = 'Howdy Jayboss'
console.log(greetings);
// varaible includes letters, numbers, special characters
// variable cannot start with a number
// multi word variable
var firstName = 'Jacob' //camel case
var first_name = 'Jayboss' //Underscore
var FirstName = 'JohnDoe' //Pascal case
// let
// let color = 'red';
// console.log(color);
// reasign variable
color = 'yellow';
console.log(color)
// initialize variable
let greetings;
greetings = 'Howdy Jayboss'
console.log(greetings);
// const (cannot be reassigned)
const name = 'Maye Jacob'
console.log(name)
// must assign vale and cannot be used to initialize variable
const person = {
name: 'jacob',
age: 30
}
Mutating
You can change the value but cant reassign the variable using const
person.name = 'Maye';
person.age = 26;
// using array
const numbers = [1,2,3,4,5,6]
// add unto it
numbers.push(7);
console.log(numbers)
Data Types
Primitive Types and Reference Types
The types can be divided into two groups: primitive types and reference types. Numbers, boolean values, and the null and undefined types are primitive. Objects, arrays, and functions are reference types.
A primitive type has a fixed size in memory. For example, a number occupies eight bytes of memory, and a boolean value can be represented with only one bit. The number type is the largest of the primitive types. If each JavaScript variable reserves eight bytes of memory, the variable can directly hold any primitive value.
Reference types are another matter, however. Objects, for example, can be of any length -- they do not have a fixed size. The same is true of arrays: an array can have any number of elements. Similarly, a function can contain any amount of JavaScript code. Since these types do not have a fixed size, their values cannot be stored directly in the eight bytes of memory associated with each variable. Instead, the variable stores a reference to the value. Typically, this reference is some form of pointer or memory address. It is not the data value itself, but it tells the variable where to look to find the value.
All primitive types, except null
, can be tested by the typeof
operator. typeof null
returns "object"
, so one has to use === null
to test for null
.
All primitive types, except null
and undefined
, have their corresponding object wrapper types, which provide useful methods for working with the primitive values. For example, the Number
object provides methods like toExponential()
. When a property is accessed on a primitive value, JavaScript automatically wraps the value into the corresponding wrapper object and accesses the property on the object instead. However, accessing a property on null
or undefined
throws a TypeError
exception, which necessitates the introduction of the optional chaining operator.
The distinction between primitive and reference types is an important one, as they behave differently. Consider the following code that uses numbers (a primitive type):
Priimitive data types
// string
const name = 'Maye Jacob';
// number
const age = 26;
// boolen
const hasKids = true;
// null
const car = null;
// undefined
let test;
// symbol
const sym = Symbol();
Reference Types - all comes back as objects
// array
const hobbies = ['cooding', 'gaming'];
console.log(typeof hobbies);
// object
const address = {
city: 'Ede',
state: 'Osun'
}
console.log(typeof address);
const today = new Date();
console.log(typeof today);
Data conversion
//let val;
// number to string
// val = 5;
val = String(5);
val = String(4+4);
// Bool to string
val = String(true);
// date to string
val = String(new Date())
// array to string
val = String([1,2,3,4,5,6,7])
// toString()
val = (5).toString();
val = (true).toString();
// string to numbers
val = '5'
val = Number('5')
val = Number(true)
val = Number(false)
val = Number(null)
// parseint
val = parseInt('100')
val = parseFloat('100.30')
// output
console.log(val);
console.log(typeof val);
// console.log(val.length); // length only works on string
console.log(val.toFixed()); // length only works on numbers
Math
const num1 = 100;
const num2 = 50;
let val;
// simple math with numbers
val = num1 + num2;
val = num1 * num2;
val = num1 - num2;
val = num1 / num2;
val = num1 % num2;
// math object
val = Math.PI;
val = Math.E;
val = Math.round(2.4); //round a number
val = Math.ceil(2.4); //round up a number
val = Math.floor(2.8); //round down a number
val = Math.sqrt(64); //square a number
val = Math.abs(-3); //absolute number
val = Math.pow(8, 2); //absolute number
val = Math.min(8,2,5,23,9); //minimum number
val = Math.max(8,2,5,23,9); //maximum number
val = Math.random(); //random decimal number
// random whole number
val = Math.random() * 20 + 1;
val = Math.floor(Math.random() * 20 + 1); //no decimal
console.log(val);
Enjoy this article ? drop a comment below and add your own contribution.
John Reply
Comment
Great content
Joshua Adejobi
Very well